类型 'NSObject?' 没有下标成员
Type 'NSObject?' has no subscript members
我已经搜索过了,真的,在这里问问题是我最后的选择......老实说,但是自从 "I had to ask" 以来,请随意对我投反对票。 .! 现在进入正题...
我有一个有两个级别的字典 "dict > keys",就是这样!但无论出于何种原因,我似乎无法获得 "three" 值。我哪里错了?
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
什么? ...尝试过:
- Why do I have "type 'NSObject' has no subscript members" error?
- [NSObject : AnyObject]?' does not have a member named 'subscript' in Xcode 6 Beta 6
函数签名中mainDict
的声明必须是[String :[String:Any]]
。或者您可以将其声明为 [String:Any]
然后,您需要将 sub 转换为 [String:Any]
所以函数应该是
func makeItPossible(mainDict : [String:Any]){
if let sub= mainDict["keys"] as [String:Any], let keyThree = sub["three"]{
print(keyThree)
}
更新为使用条件绑定。
我已经搜索过了,真的,在这里问问题是我最后的选择......老实说,但是自从 "I had to ask" 以来,请随意对我投反对票。 .! 现在进入正题...
我有一个有两个级别的字典 "dict > keys",就是这样!但无论出于何种原因,我似乎无法获得 "three" 值。我哪里错了?
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
什么? ...尝试过:
- Why do I have "type 'NSObject' has no subscript members" error?
- [NSObject : AnyObject]?' does not have a member named 'subscript' in Xcode 6 Beta 6
函数签名中mainDict
的声明必须是[String :[String:Any]]
。或者您可以将其声明为 [String:Any]
然后,您需要将 sub 转换为 [String:Any]
所以函数应该是
func makeItPossible(mainDict : [String:Any]){
if let sub= mainDict["keys"] as [String:Any], let keyThree = sub["three"]{
print(keyThree)
}
更新为使用条件绑定。