简体   繁体   中英

Supporting optional parameter value in Swift property wrapper

I have below property wrapper for user defaults,

@propertyWrapper
class MyUserDefaultWrapper<T> {
    let key: String
    let defaultValue: T

    init(_ key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            let suit = UserDefaults.standard
            return suit?.object(forKey: key) as? T ?? defaultValue
        }
        set {
            let suit = UserDefaults.standard
            suit?.set(newValue, forKey: key)
        }
    }
}

I am defining it like,

struct MyUserDefaultsCommon{
    @MyUserDefaultWrapper("yearOfBirth", defaultValue: 1980)
    static var yearOfBirth: Int
}

And calling it like,

MyUserDefaultsCommon.yearOfBirth = 2010

When I set default value to nil build is failed with a sig abrt.

How can I restrict passing optional default value from property wrapper class? Or is there any other way around?

How can I restrict passing optional default value from property wrapper class?

This is (was) a bug in Swift. It's been fixed, and should be in the next release of 5.1 . You should not be able to pass nil here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM