一个围绕 NSCache
的类型安全且 Swift 化的封装。
使用 SPM 将 swift-cache
作为依赖项添加到您的项目中。
.package(url: "https://github.com/binaryscraping/swift-cache", from: "0.1.0"),
并在您的应用程序/目标中,将 "Cache"
添加到您的 "dependencies"
。
.target(
name: "YourTarget",
dependencies: [
.product(name: "Cache", package: "swift-cache"),
]
)
Cache
通过 Cache.Key
类型访问,所以首先定义您的键。
extension Cache.Key where Value == String {
// A key that stores a string value.
static let myKey = Cache.Key("my_key")
}
实例化一个缓存类型的实时实现。
let cache = Cache.live()
cache.set("string value", at: .myKey)
您可以为条目提供一个可选的生命周期(秒)。
cache.set("string value", at: .myKey, lifetime: 60)
let value = cache.retrieve(at: .myKey)
cache.remove(at: .myKey)
这个库提供了一些助手函数,方便在测试中使用,例如
一个 Cache
的实现,当被调用时什么也不做。
let cache = Cache.noop
一个 Cache
的实现,会使用 XCTFail
调用来抛出错误。
var setEntryCalled = false
let cache = Cache.failing
.override(
setEntry: { entry, key in
setEntryCalled = true
}
)
cache.set("string value", at: .myKey)
XCTAssertTrue(setEntryCalled)
在上面的代码片段中,所有对未被重写的方法的调用都会以 XCTFail
终止。