Skip to content

Instantly share code, notes, and snippets.

@damozhang
Created July 11, 2018 21:30
Show Gist options
  • Save damozhang/6f0cdbc40f29a9fe7e4a98b8545e0e06 to your computer and use it in GitHub Desktop.
Save damozhang/6f0cdbc40f29a9fe7e4a98b8545e0e06 to your computer and use it in GitHub Desktop.
A protocol to manage cache.
import Foundation
import Disk
public protocol Cachable: Codable{
associatedtype CacheObject
var cacheName: String {get}
static func cacheId(_ id: String?) -> String
static func loadCache(cacheName: String) -> CacheObject?
static func removeCache(cacheName: String)
func saveCache() -> Bool
}
extension Cachable where CacheObject: Cachable{
static func loadCache(cacheName: String) -> CacheObject?{
do {
let cache = try Disk.retrieve(
cacheName,
from: .caches,
as: CacheObject.self
)
return cache
} catch {
return nil
}
}
static func removeCache(cacheName: String) {
do {
try Disk.remove(
cacheName,
from: .caches
)
} catch {
print("Remove cache is failure")
}
}
@discardableResult func saveCache() -> Bool{
do {
try Disk.save(
self,
to: .caches,
as: self.cacheName
)
return true
} catch {
return false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment