当我尝试访问数组类型值然后出现错误时,在字典中可能会包含数组类型值,而出现诸如“模糊引用成员下标”的错误。
请检查以下代码。

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
"Layme": ["Engineer", "Docter"]
] as [String : Any]


occupations["Jayne"] = "Public Relations"
var arrOfLayme = occupations["Layme"] as! Array //getting error here, If I use NSArray instead of array all will work as expacted
print(valueOcc[0])

当我使用NSArray键入此代码时,如下面所示,我想以一种快速的方式进行操作,不想添加Objective-c。
var arrOfLayme = occupations["Layme"] as! NSArray

最佳答案

试试这个:

var occupations:[String:Any] = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
    "Layme": ["Engineer", "Docter"]
    ]

occupations["Jayne"] = "Public Relations"


var arrOfLayme = occupations["Layme"] as! [String]
print(arrOfLayme)

//More safe
if let arr = occupations["Layme"] as? [String] {
    print(arr)
}

10-05 20:03