在 Swift 字典扩展中检查 nil 值 [英] Checking for nil Value in Swift Dictionary Extension

查看:32
本文介绍了在 Swift 字典扩展中检查 nil 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Playground 文件中有以下代码:

I have the following code in a playground file:

extension Dictionary {

    func test()  {

        for key in self.keys {
            self[key]
        }
    }
}

var dict: [String: AnyObject?] = [
    "test": nil
]

dict.test()

此后我将把 for-each 循环中的行称为输出,因为它是相关的.在此特定实例中,输出为 nil.

I will henceforth refer to the line within the for-each loop as the output since it is what's relevant. In this particular instance the output is nil.

当我将 for-each 循环更改为如下所示时:

When I change the for-each loop to look like this:

for key in self.keys {
    print(self[key])
}

输出为"Optional(nil) ".

The output is "Optional(nil) ".

我真正想做的是检查 nil 的值,但代码:

What I really want to do is check the value for nil, but the code:

for key in self.keys {
    self[key] == nil
}

输出false.

我尝试过的另一件事如下:

One other thing I tried was the following:

for key in self.keys {
    self[key] as! AnyObject? == nil
}

产生错误:

Could not cast value of type 'Swift.Optional<Swift.AnyObject>' to 'Swift.AnyObject'

非常感谢您对此的任何帮助!

Any help with this is much appreciated!

推荐答案

你已经把自己弄得一团糟,因为一个值可以为 nil 的字典为你提供了一个 nil 的前景em>double-wrapped Optional,因此有两种 nil.如果密钥丢失,您会得到 nil,然后如果密钥 丢失并且您解开包装,您会得到 nil获取的结果.不幸的是,您是在操场上进行测试,这是探索区别的糟糕场所.

You've gotten yourself into kind a mess, because a dictionary whose values can be nil presents you with the prospect of a double-wrapped Optional, and therefore two kinds of nil. There is the nil that you get if the key is missing, and then the nil that you get if the key is not missing and you unwrap the fetched result. And unfortunately, you're testing in a playground, which is a poor venue for exploring the distinction.

要明白我的意思,请考虑以下几点:

To see what I mean, consider just the following:

var d : [String:Int?] = ["Matt":1]
let val = d["Matt"]

val 的类型是什么?它是 Int?? - 一个 Int 包裹在一个 Optional 包裹在另一个 Optional 中.那是因为字典里面的值,根据定义,是一个 Int 包裹在一个 Optional 中,然后通过它的键获取值,然后将它包裹在 另一个 Optional 中.

What is the type of val? It's Int?? - an Int wrapped in an Optional wrapped in another Optional. That's because the value inside the dictionary was, by definition, an Int wrapped in an Optional, and then fetching the value by its key wraps that in another Optional.

那么现在让我们走得更远一点,这样做:

So now let's go a bit further and do it this way:

var d : [String:Int?] = ["Matt":nil]
let val = d["Matt"]

什么是val?好吧,游乐场可能它是nil,但事实要复杂得多;它是 nil 包裹在另一个 Optional 中.如果您打印 val,这是最容易看到的,在这种情况下,您得到的不是nil,而是"Optional(nil)".

What is val? Well, the playground may say it is nil, but the truth is more complicated; it's nil wrapped in another Optional. That is easiest to see if you print val, in which case you get, not nil, but "Optional(nil)".

但是如果我们尝试一些根本不存在密钥的东西,我们会得到不同的答案:

But if we try for something where the key isn't there at all, we get a different answer:

let val2 = d["Alex"]

那真的 nil,表示密钥丢失.如果我们打印 val2,我们会得到"nil".Playground 无法区分(它对 valval2 都表示 nil),但是转换为字符串(这就是 print 确实)显示了差异.

That really is nil, signifying that the key is missing. And if we print val2, we get "nil". The playground fails to make the distinction (it says nil for both val and val2), but converting to a String (which is what print does) shows the difference.

所以问题的一部分是整个双重包装的 Optional 东西,另一部分是 Playground 以一种非常误导的方式表示双重包装的 Optional.

So part of the problem is this whole double-wrapped Optional thing, and the other part is that the Playground represents a double-wrapped Optional in a very misleading way.

道德 1:值类型为 Optional 的字典可能会变得非常棘手.

MORAL 1: A dictionary whose value type is an Optional can get really tricky.

道德 2:游乐场是魔鬼的杰作.避开它们.使用真实的应用程序,并使用日志记录到控制台或调试器的变量面板,看看真正发生了什么.

MORAL 2: Playgrounds are the work of the devil. Avoid them. Use a real app, and use logging to the console, or the variables pane of the debugger, to see what's really happening.

这篇关于在 Swift 字典扩展中检查 nil 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆