ios 在 Swift 中将对象设置为空的 NSDictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24477894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:10:23  来源:igfitidea点击:

Set objects to empty NSDictionary in Swift

iosnsdictionaryswiftxcode6

提问by NNikN

I can create an NSDictionary

我可以创建一个 NSDictionary

    var namesDictionary=Dictionary<String,String>()
    namesDictionary["Jacob"] = "Marry"

But, when I create a empty dictionary like coded below, line 1 i okie, but line 2 (adding values) throws an error.

但是,当我创建一个像下面编码的空字典时,第 1 行我没问题,但是第 2 行(添加值)会引发错误。

    var namesDictionary =[:]
    namesDictionary["Jacob"] = "Marry"

Error is "Cannot assign to the result of this expression". Is there any other way to assign the values.

错误是“无法分配给此表达式的结果”。有没有其他方法来分配值。

回答by Connor

It looks like it's an issue with swift interpreting the type of your dictionary. Try explicitly typing your empty dictionary.

看起来这是快速解释字典类型的问题。尝试明确键入您的空字典。

var namesDictionary: Dictionary<String, String> = [:]
namesDictionary["Jacob"] = "Marry"

I think a better use for [:]is for emptying an already defined dictionary. If you add a third line namesDictionary = [:], you will be able to call namesDictionary["Jacob"] = "Marry"again since the compiler knows what type of dictionary it is from the inital declaration.

我认为更好的用途[:]是清空已经定义的字典。如果添加第三行namesDictionary = [:],您将能够namesDictionary["Jacob"] = "Marry"再次调用,因为编译器从初始声明中知道它是什么类型的字典。