Skip to content

Instantly share code, notes, and snippets.

@aranasaurus
Forked from IanKeen/KeyValueStorable.swift
Created September 25, 2015 03:03
Show Gist options
  • Save aranasaurus/cbbd204f403c9952e6b1 to your computer and use it in GitHub Desktop.
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
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