SwiftCache is a pure swift cache framework inspired by YYCache
- iOS 8.0+
- Xcode 8.0
- Swift 3.0
Create a Cartfile
that lists the framework and run carthage update
.
Follow the instructions to add$(SRCROOT)/Carthage/Build/iOS/SCache.framework
to an iOS project.
github "tbxark/SwiftCache"
UIImage
let imageCache = SwiftCache<String, UIImage>(name: "Image")
imageCache?.setValue(UIImage(named: "test"), withkey: "test")
let img = imageCache?.valueForKey("test")
Struct
struct CacheStruct: Cacheable {
let name: String
let value: String
static func build(_ data: Data) -> CacheStruct? {
guard let obj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
let dict = obj as? [String: String],
let n = dict["name"],
let v = dict["value"] else { return nil }
return CacheStruct(name: n, value: v)
}
func mapToData() -> Data? {
let dict = ["name": name, "value": value]
return try? JSONSerialization.data(withJSONObject: dict, options: [])
}
}
let structCache = SwiftCache<Int, CacheStruct>(name: "Struct")
let a = CacheStruct(name: "A", value: "A")
structCache?.setValue(a, withkey: 1)
if let aCache = structCache?.valueForKey(1) {
print(aCache)
}
在 OC里面 YYCache 算是最出色的一个缓存框架
我在研究 YYCache 的代码的时候就顺便用 Swift 仿写了一遍, 毕竟比起看代码, 写代码更能加深理解.
写得时候也充分的利用的 Swift语言的优势, 加上了泛型 和 Any 类型的支持(因为YYCache是 OC 写的所以只能缓存 class 类型).
YYCache High performance cache framework for iOS.
GRDB.swift A Swift application toolkit for SQLite databases
SwiftMD5 A pure Swift implementation of MD5
We would love for you to contribute to SwiftCache, check the LICENSE
file for more info.
TBXark – @tbxark – tbxark@outlook.com
Distributed under the MIT license. See LICENSE
for more information.