2
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...

Tejas Pandya
  • 3,987
  • 1
  • 26
  • 51

3 Answers3

2
if let seen = UserDefaults.standard.object(forKey: UtilitiesKeys.mainTutorialSeen)) as? Bool {
        return seen
    }else {
        return false
    }
d0ye
  • 1,580
  • 1
  • 15
  • 26
1

Apple document says:

/*! -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

Initializer for conditional binding must have Optional type, not 'Bool'

hope this help you.

iamVishal16
  • 1,780
  • 18
  • 40
0

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)
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165