Created
June 16, 2019 03:42
-
-
Save ericlewis/8fe3b7903d5ad8de4fb9f401bb2da1c6 to your computer and use it in GitHub Desktop.
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 | |
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