Search code examples
swiftoption-typeuserdefaults

How to safely unwrap a value from user defaults?


if let seen: Bool = defaults.bool(forKey: UtilitiesKeys.mainTutorialSeen) {
    return seen
}
return false

if i do this swift shows me an issue:

Conditional cast from 'Bool' to 'Bool' always succeeds, Non-optional expression of type 'Bool' used in a check for optionals.

Since there might not be a value for my key, I don't want to force unwrap it. Now obviously it's working like this, but how do I safely unwrap the value without having swift complaining?

I have tried to use guard as well...


Solution

  • As suggested in doc:

    -boolForKey: is equivalent to -objectForKey:, except that it converts the returned value to a BOOL. If the value is an NSNumber, NO will be returned if the value is 0, YES otherwise. If the value is an NSString, values of "YES" or "1" will return YES, and values of "NO", "0", or any other string will return NO. If the value is absent or can't be converted to a BOOL, NO will be returned.

    open func bool(forKey defaultName: String) -> Bool
    

    It is not an optional anymore. So you don't need to cast it with if let.

    You can directly use:

    let seen = defaults.bool(forKey: UtilitiesKeys.mainTutorialSeen)