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

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

问题描述

我在操场文件中有以下代码:

 扩展字典{

func test (){

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

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

dict.test()
pre>

我以后会将for-each循环中的行引用为输出,因为它是相关的。在这个特殊情况下,输出是 nil



当我将每个循环更改为如下所示:

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

输出是可选(nil)\\\



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

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

输出 false



我尝试的另一件事是:

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

产生错误:

 无法将Swift.Optional< Swift.AnyObject>类型的值转换为Swift.AnyObject
/ pre>

任何帮助,非常感谢!

解决方案

你已经把自己变得一团糟了,因为价值可以是 nil 的字典向您展示了一个双面可选的前景,因此两种 nil 。如果密钥丢失,您将获得 nil ,然后如果密钥为code $ n缺少 ,您可以解开获取的结果。不幸的是,您正在一个游乐场进行测试,这是一个探索这个区别的不好的场所。



要查看我的意思,请考虑以下内容:

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

val 的类型是什么?它是 Int ?? - 一个Int包装在一个可选包装另一个可选。这是因为根据定义,字典内的 中的值是根据定义包装在可选中的Int,然后通过其键包裹获取值,在另一个可选。



所以现在我们再来一点,这样做:

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

什么是 val ?那么操场可能会说它是 nil ,但事实更复杂; nil 包装在另一个可选中。这是最容易看到你是否打印 val ,在这种情况下你得到,而不是 nil ,但可选(nil)



但是,如果我们尝试关键不是在那里,我们得到一个不同的答案:

  let val2 = d [Alex] 

真的 nil ,表示该键丢失。如果我们打印 val2 ,我们得到nil。操场无法区分(对于 val val2 , nil code>),但转换成一个String(这是什么 print )会显示出差异。



所以问题的一部分是这个整个双包装可选的东西,另一部分是Playground代表一个双包装可选的一个非常误导的方式。



MORAL 1 :价值类型为可选的字典可能非常棘手。



MORAL 2 :游乐场恶魔的工作。避免他们使用真正的应用程序,并使用日志记录到控制台或调试器的变量窗格,以查看真正发生的情况。


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()

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.

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

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

The output is "Optional(nil)\n".

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

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

outputs false.

One other thing I tried was the following:

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

which produces the error:

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

Any help with this is much appreciated!

解决方案

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"]

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"]

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"]

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.

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.

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

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字典扩展中检查零值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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