ios - 为什么 if(nil) 被评估为 true?

标签 ios swift

我正在尝试检查 NSDictionary 中是否存在某个键,然后处理该案例。但是,当值为 nil 时,为什么这种情况得到满足?

results: NSDictionary
println(results)

打印这个:

{
    error = (
        {
            code = 402;
            message = "User exists for this email";
            username = "xyz@gmail.com";
        }
    );
}

但是当我 checkin if block 时,为什么是进入内部?

    if(results["results"])
    {
      println("why here?");
    }

这里 if(nil) 应该会失败,但事实并非如此。 我还尝试使用 results.valueForKey("results")、results.objectForKey("results"),但它们都给出了异常。

如果我使用它,它会因运行时错误而崩溃:

if let dict: results["results"]

更新: 刚刚发现第一次正确求值后控件跳转到函数开头,然后运行时发生。那么为什么函数会循环两次然后崩溃呢?

最佳答案

这不是我看到的行为。以下代码按预期打印 "just what I expect"

let results: NSDictionary = ["foo": "bar"]

if results["baz"] {
    println("why here?");
} else {
    println("just what I expect");
}

一定有其他问题没有包含在您的问题中。

关于ios - 为什么 if(nil) 被评估为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24562751/

相关文章:

ios - 是否有常见 OpenGL 着色器的常用来源?

ios - Swift:设置 ABRecord 的地址属性

ios - float 操作按钮的中心 UIButton 文本,如收件箱应用程序

javascript - Cloudkit JS && Node JS

swift - 在 swift 的条件转场中获取 NSInternalInconsistencyException

ios - 当应用程序在 SWIFT 中进入前台时如何呈现 Lock_ViewController?

ios - UICollectionView didSelectRowAt 从未被调用

ios - 如何使用委托(delegate)来指示哪个 View Controller 充当初始 View Controller ?

ios - Swift WKWebView 未初始化并导致意外的 nil 错误

ios - 在 iOS 的 Tableview 单元格上自动播放视频