I'm creating a property wrapper for UserDefaults
.
What i'm trying to achieve is:
- Setting a non-nil value to property will store it in User default.
- Setting nil will remove the Object from UserDefault.
But below code throws compiler error:
Initializer for conditional binding must have Optional type, not 'T'
@propertyWrapper
struct UserDefault<T> {
let key: String
let defaultValue: T
init(_ key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get { UserDefaults.standard.value(forKey: key) as? T ?? defaultValue }
set {
if let newValue = newValue {
UserDefaults.standard.setValue(newValue, forKey: key)
} else {
UserDefaults.standard.removeObject(forKey: key)
}
}
}
}
// Declaration
@UserDefault("key", defaultValue: nil)
static var newUserDefaultValue: String
Is there any way to identify T is optional? as I can remove the key from UserDefaults. If not how to achieve the desired output?
T
is optional then expressionas? T
returnsT?
so for concrete type you will have for exampleas? Bool?
which isBool??
. This case is discussed in greater detail in the article dev.to/kodelit/… – kodelit