输入'NSObject?'没有下标成员

时间:2017-02-03 07:58:46

标签: swift xcode macos swift3 macos-sierra

我已经搜索过了,真的,在这里问一个问题是我的最后一招......老实说,但是我可以随心所欲地向我发出警告,因为“我不得不问”......! / em>现在开始营业......

我有一个带有两个级别“dict>键”的字典,就是这样!但无论出于何种原因,我似乎无法获得“三”价值。我在哪里出错?

print(mainDict)

/*
 ["keys": {
     one = "one...";
     two = 2;
     three = "three"; // need this one!
 }]
*/

let sub = mainDict["keys"]
print(sub as Any)

/*
 Optional({
     one = "one...";
     two = 2;
     three = "three";
 })
*/

大!到目前为止这么好......但是那时候:

let keyThree = mainDict["three"]
print(keyThree as Any)
// nil

let keyThree = sub["three"]
// Type 'NSObject?' has no subscript members

WTH? ......试过:

1 个答案:

答案 0 :(得分:2)

函数签名中mainDict的声明必须为[String :[String:Any]]。或者您可以将其声明为[String:Any]然后,您需要将子广告投放为[String:Any]

所以函数应该是

func makeItPossible(mainDict : [String:Any]){
   if let sub= mainDict["keys"] as [String:Any], let keyThree = sub["three"]{
        print(keyThree)
}

更新为使用条件绑定。