Created
July 21, 2016 06:10
-
-
Save jakecraige/1bbc28b8a69a12138e2006e6f7d61986 to your computer and use it in GitHub Desktop.
This file contains 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
private func cacheError(message: String) -> NSError { | |
return NSError( | |
domain: "", | |
code: 0, | |
userInfo: [NSLocalizedDescriptionKey: message] | |
) | |
} | |
class MyCacheDelegate: CacheDelegate { | |
private var modelCache: [String: SimpleModel] = [:] | |
private var collectionCache: [String: [SimpleModel]] = [:] | |
func modelForKey<T : SimpleModel>(cacheKey: String?, context: Any?, completion: (T?, NSError?) -> ()) { | |
guard let cacheKey = cacheKey else { | |
return completion(.None, cacheError("cacheKey argument required")) | |
} | |
guard let model = modelCache[cacheKey] as? T else { | |
return completion(.None, cacheError( | |
"Object '\(String(T))' not found for key '\(cacheKey)'" | |
)) | |
} | |
completion(model, .None) | |
} | |
func setModel<T: SimpleModel>(model: T, forKey cacheKey: String, context: Any?) { | |
modelCache[cacheKey] = model | |
} | |
func collectionForKey<T: SimpleModel>(cacheKey: String?, context: Any?, completion: ([T]?, NSError?) -> ()) { | |
guard let cacheKey = cacheKey else { | |
return completion(.None, cacheError("cacheKey argument required")) | |
} | |
guard let model = collectionCache[cacheKey] as? [T] else { | |
return completion(.None, cacheError( | |
"Object '\(String(T))' not found for key '\(cacheKey)'" | |
)) | |
} | |
completion(model, .None) | |
} | |
func setCollection<T: SimpleModel>(collection: [T], forKey cacheKey: String, context: Any?) { | |
collectionCache[cacheKey] = collection.map { $0 as SimpleModel } | |
} | |
func deleteModel(model: SimpleModel, forKey cacheKey: String?, context: Any?) { | |
guard let cacheKey = cacheKey else { return } | |
modelCache.removeValueForKey(cacheKey) | |
collectionCache.removeValueForKey(cacheKey) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment