MST

星途 面试题库

面试题:Swift 泛型数据类型的高级应用

假设你需要实现一个通用的缓存系统,用于缓存不同类型的数据。请使用 Swift 泛型来设计这个缓存系统,包括缓存数据的存储、读取、更新和删除操作,同时要考虑缓存的容量限制以及数据过期机制。请提供完整的代码实现,并解释设计思路。
39.8万 热度难度
编程语言Swift

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 泛型使用:通过泛型 Cache 结构体可以存储不同类型的数据。
  2. 缓存容量限制:使用 maxCapacity 来控制缓存的最大容量,当缓存满时,采用简单的策略(如删除最早插入的数据)。
  3. 数据过期机制:为每个缓存项添加 expiryDate 字段,每次读取或更新时检查数据是否过期。

代码实现

import Foundation

struct CacheItem<T> {
    let value: T
    let expiryDate: Date
}

struct Cache<T> {
    private var items: [String: CacheItem<T>] = [:]
    private let maxCapacity: Int
    private var currentCount: Int = 0

    init(maxCapacity: Int) {
        self.maxCapacity = maxCapacity
    }

    func get(key: String) -> T? {
        guard let item = items[key] else { return nil }
        if item.expiryDate < Date() {
            items.removeValue(forKey: key)
            currentCount -= 1
            return nil
        }
        return item.value
    }

    func set(key: String, value: T, expiration: TimeInterval) {
        if items.keys.contains(key) {
            items[key] = CacheItem(value: value, expiryDate: Date().addingTimeInterval(expiration))
            return
        }
        if currentCount >= maxCapacity {
            let sortedItems = items.sorted { $0.value.expiryDate < $1.value.expiryDate }
            let keyToRemove = sortedItems.first?.key
            items.removeValue(forKey: keyToRemove)
            currentCount -= 1
        }
        items[key] = CacheItem(value: value, expiryDate: Date().addingTimeInterval(expiration))
        currentCount += 1
    }

    func update(key: String, value: T, expiration: TimeInterval) {
        set(key: key, value: value, expiration: expiration)
    }

    func delete(key: String) {
        if items.keys.contains(key) {
            items.removeValue(forKey: key)
            currentCount -= 1
        }
    }
}

你可以这样使用这个缓存系统:

let cache = Cache<String>(maxCapacity: 10)
cache.set(key: "key1", value: "value1", expiration: 60)
if let value = cache.get(key: "key1") {
    print("Retrieved value: \(value)")
}
cache.update(key: "key1", value: "newValue1", expiration: 30)
cache.delete(key: "key1")