Created
November 4, 2019 05:46
-
-
Save NeilsUltimateLab/a2bff1b70106b318656adcab2feee7a6 to your computer and use it in GitHub Desktop.
Property Wrapper for User Defaults.
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
@propertyWrapper | |
struct UserDefaulter<A: RawRepresentable> { | |
let key: String | |
init(_ key: String) { | |
self.key = key | |
} | |
private var fetchedValue: A? | |
var wrappedValue: A? { | |
mutating get { | |
if let fetchedValue = fetchedValue { | |
return fetchedValue | |
} | |
if let rawValue = UserDefaults.standard.value(forKey: key) as? A.RawValue { | |
let result = A(rawValue: rawValue) | |
self.fetchedValue = result | |
return result | |
} | |
return nil | |
} | |
set { | |
UserDefaults.standard.set(newValue?.rawValue, forKey: key) | |
self.fetchedValue = newValue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment