Last active
April 12, 2020 12:45
-
-
Save chanonly123/301bf961881c81cb5dcc371c3611c6ca to your computer and use it in GitHub Desktop.
Simple propertyWrapper for UserDefaults
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
@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