Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/101.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 斯威夫特:“我的名字叫什么?”;任何;没有名为元素的成员_Ios_Swift_Ios8 - Fatal编程技术网

Ios 斯威夫特:“我的名字叫什么?”;任何;没有名为元素的成员

Ios 斯威夫特:“我的名字叫什么?”;任何;没有名为元素的成员,ios,swift,ios8,Ios,Swift,Ios8,所以不确定这里出了什么问题,但是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: [[S

所以不确定这里出了什么问题,但是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更改为string(注意,我没有触及boolean),也将Any更改为string

请解释一下这种行为


谢谢

如果您编写了一个复杂的字典文本,如
[“id”:1,“text”:“您的名字是什么?”]
而不以某种方式注释类型,则默认情况下将创建一个
NSDictionary

Swift中的
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
]

它确实管用,但我仍在努力解决
Any
。如果不能处理复杂的模式,
Any
AnyObject
Dictionary
通常有什么好处。仅供参考-即使我使用
AnyObject
,上述操作也会引发错误。也许我需要更好地理解底层API。事实上,如果您不使用这种类型的bar,它会在
[String:AnyObject]
中崩溃。哦,您可能还需要像下面这样展开下标的结果
bar[“questions”]