-
-
Save aranasaurus/cbbd204f403c9952e6b1 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
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
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) | |
} | |
} | |
} | |
struct StringDictionary: KeyValueStorable { | |
var dictionary = [String: AnyObject]() | |
subscript (key: String) -> AnyObject? { | |
get { return self.dictionary[key] } | |
set { self.dictionary[key] = newValue } | |
} | |
mutating func removeAll() { dictionary.removeAll() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment