Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@propertyWrapper
public struct UserDefault<T>: UserDefaultSpec {
let key: String
let defaultValue: T
public init(_ key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
public var value: T {
get {
UserDefaults.standard[key] ?? defaultValue
}
set {
UserDefaults.standard[key] = newValue
}
}
}
// GRRR why don't you work?!
public extension UserDefault where T: RawRepresentable {
var value: T {
get {
if let rawValue = UserDefaults.standard.value(forKey: key) as? T.RawValue {
return T(rawValue: rawValue)!
}
return defaultValue
}
set {
UserDefaults.standard.set(newValue.rawValue, forKey: key)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.