Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save calvingit/e9bc4532e4515013669fe316a429a1c3 to your computer and use it in GitHub Desktop.

Select an option

Save calvingit/e9bc4532e4515013669fe316a429a1c3 to your computer and use it in GitHub Desktop.
// 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