如何在Swift字典中添加nil值? [英] How to add nil value to Swift Dictionary?
问题描述
我已经在我的应用中向服务器提出了请求.然后像这样发布数据.服务器端正在等待所有参数,即使它们为零.但是我无法将nil值添加到字典中.
I have made a request to my server in my app. And posted data something like this.Server side is waiting for all parameters even they are nil. But i couldn't add nil values to dictionary.
var postDict = Dictionary<String,AnyObject>
postDict[pass]=123
postDict[name]="ali"
postDict[surname]=nil // dictionary still has only pass and name variables.
有没有一种方法可以将nil值添加到字典中?
Is there a way to add nil value to dictionary ?
推荐答案
如何在Swift字典中添加
nil
值?
基本上与您将其他任何值添加到字典的方式相同.您首先需要一个字典,该字典的值类型可以保存您的值.类型AnyObject
不能具有值nil
.因此,类型为[String : AnyObject]
的字典不能具有值nil
.
Basically the same way you add any other value to a dictionary. You first need a dictionary which has a value type that can hold your value. The type AnyObject
cannot have a value nil
. So a dictionary of type [String : AnyObject]
cannot have a value nil
.
如果您的字典的值类型是可选类型,例如[String : AnyObject?]
,则它可以容纳nil
值.例如,
If you had a dictionary with a value type that was an optional type, like [String : AnyObject?]
, then it can hold nil
values. For example,
let x : [String : AnyObject?] = ["foo" : nil]
如果您要使用下标语法来分配元素,则有些棘手.请注意,类型[K:V]
的下标具有类型V?
.可选的是,当您找到它时,它指示是否有该键的条目,如果有,则指示该值;并将其放入后,您可以设置一个值或删除该条目(通过分配nil
).
If you want to use the subscript syntax to assign an element, it is a little tricky. Note that a subscript of type [K:V]
has type V?
. The optional is for, when you get it out, indicating whether there is an entry for that key or not, and if so, the value; and when you put it in, it allows you to either set a value or remove the entry (by assigning nil
).
这意味着对于我们的类型为[String : AnyObject?]
的字典,下标的类型为AnyObject??
.同样,当您在下标中输入值时,外部"可选选项允许您设置值或删除条目.如果我们只是写
That means for our dictionary of type [String : AnyObject?]
, the subscript has type AnyObject??
. Again, when you put a value into the subscript, the "outer" optional allows you to set a value or remove the entry. If we simply wrote
x["foo"] = nil
编译器推断出它是类型为AnyObject??
的nil
(外部可选),这意味着删除键"foo"
的条目.
the compiler infers that to be nil
of type AnyObject??
, the outer optional, which would mean remove the entry for key "foo"
.
为了将键"foo"
的值设置为AnyObject?
值nil
,我们需要传入一个非nil
外部可选内容,其中包含一个内部可选内容(值nil
的AnyObject?
类型).为此,我们可以
In order to set the value for key "foo"
to the AnyObject?
value nil
, we need to pass in a non-nil
outer optional, containing an inner optional (of type AnyObject?
) of value nil
. In order to do this, we can do
let v : AnyObject? = nil
x["foo"] = v
或
x["foo"] = nil as AnyObject?
表明我们的nil
为AnyObject?
而不是AnyObject??
的任何内容.
Anything that indicates that we have a nil
of AnyObject?
, and not AnyObject??
.
这篇关于如何在Swift字典中添加nil值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!