Created
November 4, 2023 11:41
-
-
Save calvingit/e9bc4532e4515013669fe316a429a1c3 to your computer and use it in GitHub Desktop.
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
| // AppStorage 需要 iOS 14 才可以用 | |
| @propertyWrapper | |
| public struct UserDefault<Value>: DynamicProperty { | |
| @State private var value: Value | |
| let key: String | |
| let store: UserDefaults | |
| public init( | |
| wrappedValue: Value, | |
| _ key: String, | |
| store: UserDefaults = .standard | |
| ) { | |
| self.key = key | |
| self.store = store | |
| let value = (store.object(forKey: key) as? Value) ?? wrappedValue | |
| self._value = State(wrappedValue: value) | |
| } | |
| public var wrappedValue: Value { | |
| get { | |
| value | |
| } | |
| nonmutating set { | |
| store.set(newValue, forKey: key) | |
| value = newValue | |
| } | |
| } | |
| public var projectedValue: Binding<Value> { | |
| .init( | |
| get: { wrappedValue }, | |
| set: { wrappedValue = $0 } | |
| ) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment