ios - 检查 `if let` 是否为零

标签 ios swift option-type unwrap

我有一个应用程序,我目前正在使用 SwiftKeychainWrapper .下面是我检查 retrievedString 是否为 nil 的代码。但是,我仍然在控制台中收到 retrievedString: nil

if-let 语句中的代码不应该运行,还是我对 if-let 的使用/理解不正确?

对于给定的示例,使用 if-let 解包我的可选值的正确方法是什么?

if let retrievedString: String? = KeychainWrapper.stringForKey("username") {
    print("retrievedString: \(retrievedString)")
    //value not nil
} else {
    //Value is nil
}

最佳答案

这是因为您正在将可选字符串 String? KeychainWrapper.stringForKey("username") 的值设置为另一个可选字符串 retrievedString.

通过尝试将一个 String? 设置为另一个 String?,if let 检查总是成功,即使值为 nil,因为这两种类型是相同的,并且都可以接受 nil 值。

相反,您应该尝试将可选字符串 String? 设置为非可选字符串 String。当 Swift 尝试将非可选的 String 设置为 nil 时,它将失败,因为非可选的不能有 nil 值。然后代码将在 else 语句中继续

你应该使用

//notice the removal of the question mark
//                            |
//                            v
if let retrievedString: String = KeychainWrapper.stringForKey("username") {
    print("retrievedString: \(retrievedString)")
    //value not nil
} else {
    //value is nil
}

关于ios - 检查 `if let` 是否为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35518417/

相关文章:

ios - 缩放图像以填充后,SwiftUI边缘变得可见

ios - iOS SDK 发送 SNS 通知的消息格式是什么?

ios - swift : Map function found nil while unwrapping an Optional value

json - Realm + Swift,嵌套 JSON

ios - Xcode Swift 2 变量声明(实例成员不能用于类型 View Controller )

iphone - 有没有办法在 cocos2d 中为 UIKit 复制 moveTo 方法?

ios - 警告 'fileAttributesAtPath :traverseLink is deprecated: first deprecated in ios 2. 0

c++ - 无法从 'auto' 推断出 'tuple_cat'

ios - 为什么我得到一个 "Value of optional type UIFont not unwrapped",但解包给出 "unexpectedly found nil while unwrapping an optional"?

c++ - 普通默认可构造的 std::optional 和 std::variant