面试题答案
一键面试设计思路
- 泛型使用:通过泛型
Cache
结构体可以存储不同类型的数据。 - 缓存容量限制:使用
maxCapacity
来控制缓存的最大容量,当缓存满时,采用简单的策略(如删除最早插入的数据)。 - 数据过期机制:为每个缓存项添加
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")