Skip to content

Instantly share code, notes, and snippets.

@chanonly123
Last active April 12, 2020 12:45
Show Gist options
  • Save chanonly123/301bf961881c81cb5dcc371c3611c6ca to your computer and use it in GitHub Desktop.
Save chanonly123/301bf961881c81cb5dcc371c3611c6ca to your computer and use it in GitHub Desktop.
Simple propertyWrapper for UserDefaults
@propertyWrapper
class UserDefaultsExtended<Type: Codable> {
let key: String
let loc: UserDefaults
var actualValue: Type?
init(key: String, loc: UserDefaults = UserDefaults.standard) {
self.key = key
self.loc = loc
}
var wrappedValue: Type? {
set {
actualValue = newValue
if let obj = newValue {
if let data = try? JSONEncoder().encode(obj) {
loc.set(data, forKey: mixKey)
loc.synchronize()
}
} else {
loc.set(nil, forKey: mixKey)
loc.synchronize()
}
}
get {
if actualValue == nil {
if let data = loc.value(forKey: mixKey) as? Data {
actualValue = try? JSONDecoder().decode(Type.self, from: data)
}
}
return actualValue
}
}
private lazy var mixKey = "\(key)"
}
class UserDefaultsItems {
@UserDefaultsExtended(key: "isLoggedIn")
static var isLoggedIn: Bool?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment