Skip to content

Instantly share code, notes, and snippets.

@NeilsUltimateLab
Created November 4, 2019 05:46
Show Gist options
  • Save NeilsUltimateLab/a2bff1b70106b318656adcab2feee7a6 to your computer and use it in GitHub Desktop.
Save NeilsUltimateLab/a2bff1b70106b318656adcab2feee7a6 to your computer and use it in GitHub Desktop.
Property Wrapper for User Defaults.
@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