Last active
July 29, 2019 12:19
-
-
Save embassem/d3dd4af3f9dc8cd2e7d753b8b46b4116 to your computer and use it in GitHub Desktop.
wrapper around UserDefaults
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
protocol PersistenceKey { | |
var key:String { get } | |
} | |
enum User:String, PersistenceKey { | |
var key: String { | |
return self.rawValue | |
} | |
case login | |
case data | |
} | |
final class Persistence { | |
private let defaults: UserDefaults | |
static private var shared: Persistence = Persistence() | |
init(defaults: UserDefaults = .standard) { | |
self.defaults = defaults | |
} | |
static subscript(key: PersistenceKey) -> String? { | |
get { | |
return self.shared.defaults.string(forKey: key.key) | |
} | |
set { | |
self.shared.defaults.set(newValue, forKey: key.key) | |
#if DEBUG | |
print("Persistence \(key.key) has changed to : \(String(describing: newValue))") | |
#endif | |
} | |
} | |
static subscript(key: PersistenceKey) -> Data? { | |
get { | |
return self.shared.defaults.data(forKey: key.key) | |
} | |
set { | |
self.shared.defaults.setValue(newValue, forKey: key.key) | |
} | |
} | |
static subscript(key: PersistenceKey) -> [Any]? { | |
get { | |
return self.shared.defaults.array(forKey: key.key) | |
} | |
set { | |
self.shared.defaults.setValue(newValue, forKey: key.key) | |
} | |
} | |
} | |
/* | |
// set | |
Persistence[User.login] = "Disconnect me. I’d rather be nothing" | |
// get | |
print(Persistence[User.login]) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment