找到你要的答案

Q:Define dictionary without Types gives compiler error in Swift

Q:定义没有类型的字典会使编译器出错

I don't know the datatypes ahead of time, how can I add data to the empty dictionary without types. Looks like someone asked the same question here but no answer was accepted How to create Dictionary that can hold anything in Key? or all the possible type it capable to hold

Swift Compiler Error:

Cannot assign to the result of this expression.

I get this error in b["test"] = 23 this line.

var a = [String:Int]()
a["test"] = 23  # Works 


var b = [:]
b["test"] = 23 # Compiler Error

我不知道数据类型前面的时候,我怎么能将数据添加到空的字典没有类型。看起来有人问同样的问题,但没有答案被接受如何创建字典,可以持有任何关键?或所有可能的类型,它能够举行

快速编译错误:

无法指定此表达式的结果。

我得到这个错误在B [测试] = 23这一行。

var a = [String:Int]()
a["test"] = 23  # W或ks 


var b = [:]
b["test"] = 23 # Compiler Err或
answer1: 回答1:

In your example, b is of type NSDictionary, which is immutable. Therefore you get an error when trying to modify its contents.

You need to declare b as an NSMutableDictionary to make this work:

let dictionary: NSMutableDictionary = [:]
dictionary["key"] = "value" // No errors.

在你的例子中,B型的会,这是不可改变的。因此,当试图修改其内容时会出错。

你需要声明B为nsmutabledictionary使这项工作:

let dictionary: NSMutableDictionary = [:]
dictionary["key"] = "value" // No err或s.
answer2: 回答2:

You can declare you second dictionary as a Swift dictionary as well, but with AnyObject as the value type:

var b = [String:AnyObject]()

Then you can do:

b["test"] = 23
b["stuff"] = "hello world"

This value will be of type AnyObject, so you have to cast it back when you retrieve it:

let result = b["test"] as! Int
let sentence = b["stuff"] as! String

or

if let result = b["test"] as? Int {
    // use result (23)
}
if let sentence = b["stuff"] as? String {
    // use sentence ("hello world")
}

你可以声明你的第二个词典快速词典为好,但以AnyObject为值类型:

var b = [String:AnyObject]()

然后你可以做:

b["test"] = 23
b["stuff"] = "hello w或ld"

此值将类型的任何物体,所以你要把它当你找回它:

let result = b["test"] as! Int
let sentence = b["stuff"] as! String

if let result = b["test"] as? Int {
    // use result (23)
}
if let sentence = b["stuff"] as? String {
    // use sentence ("hello w或ld")
}
answer3: 回答3:
var b:[NSObject:AnyObject] = [:]
b["test"] = 23
b[1] = "one"
b // ["test": 23, 1: "one"]
var b:[NSObject:AnyObject] = [:]
b["test"] = 23
b[1] = "one"
b // ["test": 23, 1: "one"]
swift  data-structures