Created
July 11, 2018 21:30
-
-
Save damozhang/6f0cdbc40f29a9fe7e4a98b8545e0e06 to your computer and use it in GitHub Desktop.
A protocol to manage cache.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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