Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active November 1, 2015 18:38
Show Gist options
  • Save IanKeen/243c7fe246fde3ab04a0 to your computer and use it in GitHub Desktop.
Save IanKeen/243c7fe246fde3ab04a0 to your computer and use it in GitHub Desktop.
A protocol I like to use in my apps anywhere something like NSUserDefaults or KeyChain is normally used... allows for easy swapping of implementation. Also provided is StringDictionary() which can be used when testing
protocol KeyValueStorable {
subscript (key: String) -> AnyObject? { get set }
mutating func removeAll() -> Void
}
extension NSUserDefaults: KeyValueStorable {
subscript (key: String) -> AnyObject? {
get { return self.objectForKey(key) }
set { self.setObject(newValue, forKey: key) }
}
func removeAll() {
self.dictionaryRepresentation().keys.forEach { key in
self.removeObjectForKey(key)
}
}
}
class StringDictionary: KeyValueStorable {
var dictionary = [String: AnyObject]()
subscript (key: String) -> AnyObject? {
get { return self.dictionary[key] }
set {
if let newValue = newValue {
self.dictionary.updateValue(newValue, forKey: key)
} else {
self.dictionary.removeValueForKey(key)
}
}
}
func removeAll() { dictionary.removeAll() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment