所以不确定这里有什么问题,但是在这种情况下swift引发了我的错误,并且没有给我foo[0]
的输出
let bar: [String: Any] = [
"questions":[
["id":1,"text":"What is your name?"],
["id":2,"text":"What is the last name?"]
],
"status":"baz",
"registered": true
]
let foo: [[String: Any]] = bar["questions"] as [[String: Any]]
foo[0]
虽然如果我这样做会有效 -
let bar: [String: String] = [
"questions":[
["id":"1","text":"What is your name?"],
["id":"2","text":"What is the last name?"]
],
"status":"AUTHENTICATE",
"registered": true
]
let foo: [[String: String]] = bar["questions"] as [[String: String]]
foo[0]
我将我的ID更改为字符串(注意我没有触及布尔值)以及Any更改为字符串。
请为这种行为说清楚。
谢谢
答案 0 :(得分:2)
如果你编写一个复杂的字典文字,如["id":1,"text":"What is your name?"]
而没有以某种方式注释该类型,它将默认创建一个NSDictionary
。
NSDictionary
桥接到[NSObject: AnyObject]
。强制将其强制转换为[String: Any]
会因错误而崩溃"无法重新解释不同大小的广告值"。但是将NSDictionary
投射到[String: AnyObject]
会很好。
因此,您可以使用[String: AnyObject]
或NSDictionary
代替[String: Any]
,也可以提示所需词典的类型,例如:
let bar: [String: Any] = [
"questions":[
["id":1,"text":"What is your name?"] as [String: Any],
["id":2,"text":"What is the last name?"]
],
"status":"baz",
"registered": true
]
或者像这样
let bar: [String: Any] = [
"questions":[
["id":1,"text":"What is your name?"],
["id":2,"text":"What is the last name?"]
] as [[String: Any]],
"status":"baz",
"registered": true
]