4

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?

Maysam
  • 7,246
  • 13
  • 68
  • 106

1 Answers1

1

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.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • 1
    What a dumdum I am! thanks, It was optional before adding the `defaultValue` and I forgot to remove the `?`. – Maysam Feb 27 '20 at 18:47
  • So does the fact that the original code compiles on Xcode 11.0 mean that it was actually a compiler bug in Swift 5.1, and got fixed in 5.1.3? – Sweeper Feb 27 '20 at 20:03
  • I don’t know, but I think the compiler error is appropriate. It doesn’t make sense for a non-optional property to have an optional `wrappedValue`. – Rob Feb 27 '20 at 20:42