Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create UserDefaults property wrapper in Swift #926

Open
onmyway133 opened this issue Jul 3, 2023 · 0 comments
Open

How to create UserDefaults property wrapper in Swift #926

onmyway133 opened this issue Jul 3, 2023 · 0 comments

Comments

@onmyway133
Copy link
Owner

onmyway133 commented Jul 3, 2023

Like AppStorage, we can make a custom UserDefaults property wrapper that conforms to DynamicProperty

@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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant