Created
September 10, 2020 22:47
-
-
Save IanKeen/c2d6926ef3256efa90a1e899fe69abf4 to your computer and use it in GitHub Desktop.
PropertyWrapper: AppStorage backport
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 AppStorage<Value>: DynamicProperty { | |
let key: String | |
let defaultValue: Value | |
init(wrappedValue defaultValue: Value, _ key: String) { | |
self.key = key | |
self.defaultValue = defaultValue | |
self._wrappedValue = State(wrappedValue: UserDefaults.standard.object(forKey: key) as? Value ?? defaultValue) | |
} | |
@State var wrappedValue: Value { | |
didSet { UserDefaults.standard.set(wrappedValue, forKey: key) } | |
} | |
var projectedValue: Binding<Value> { | |
return Binding( | |
get: { wrappedValue }, | |
set: { wrappedValue = $0 } | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment