Swift properyWrapper cannot convert value of declared type to value of specified type

Viewed 547

Here is my property wrapper:

@propertyWrapper struct UserDefaultsBacked<Value> {
    let key: String
    let storage: UserDefaults = .standard
    var defaultValue: Value

    var wrappedValue: Value? {
        get {
            let value = storage.value(forKey: key) as? Value
            return value ?? defaultValue
        }
        set { storage.setValue(newValue, forKey: key) }
    }
}

And this variable, snapStatus, is supposed to have a boolean value, right?

@UserDefaultsBacked(key: "snap-is-enabled", defaultValue: false)
var snapStatus: Bool

But compiler throws an error:

Cannot convert value of type 'UserDefaultsBacked' to specified type 'Bool'

enter image description here

Am I doing it the wrong way?

1 Answers

You’ve declared wrappedValue as an optional, e.g. Value?. Change it to not be an optional and the error will go away:

@propertyWrapper struct UserDefaultsBacked<Value> {
    let key: String
    let storage: UserDefaults = .standard
    var defaultValue: Value

    var wrappedValue: Value {   // not `Value?`
        get {
            let value = storage.value(forKey: key) as? Value
            return value ?? defaultValue
        }
        set { storage.setValue(newValue, forKey: key) }
    }
}

Alternatively, you could keep wrappedValue as is, but then you’d have to declare snapStatus as an optional:

var snapStatus: Bool?

I think the elimination of the optionals is the way to go, but I include this for the sake of completeness.

Related