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

4

3 回答 3

2
if let seen = UserDefaults.standard.object(forKey: UtilitiesKeys.mainTutorialSeen)) as? Bool {
        return seen
    }else {
        return false
    }
于 2017-12-20T06:41:20.503 回答
1

苹果文件说:

/*!-boolForKey: 等价于 -objectForKey:,不同之处在于它将返回值转换为 BOOL。如果值为 NSNumber,如果值为 0,则返回 NO,否则返回 YES。如果值为 NSString,“YES”或“1”的值将返回 YES,“NO”、“0”或任何其他字符串的值将返回 NO。如果该值不存在或无法转换为 BOOL,则将返回 NO。

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

条件绑定的初始化程序必须具有 Optional 类型,而不是 'Bool'

希望这对你有帮助。

于 2017-12-20T06:45:54.957 回答
0

正如文档中所建议的:

-boolForKey:等效于-objectForKey:,只是它将返回的值转换为BOOL。如果值为, 如果值为NSNumber,NO将返回0YES否则返回。如果值为 an NSString,则返回"YES"or的值,返回, 或任何其他字符串的值。如果该值不存在或无法转换为,将被返回。"1"YES"NO""0"NOBOOLNO

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

它不再是可选的。所以你不需要用if let.

您可以直接使用:

let seen = defaults.bool(forKey: UtilitiesKeys.mainTutorialSeen)
于 2017-12-20T06:44:40.650 回答