Argument Type 'AnyObject' does not conform to expected type NSCopying

末鹿安然 提交于 2019-12-12 03:36:45

问题


I am trying to use NSDictionary in Swift and I am facing the above-mentioned problem. I have a dictionary of the following format:

let xyz: NSMutableDictionary = ["1":[1,2,3,4,"1","n","1","2"],"2":[1,2,3,4,"+","o","6","2"]]

I want to iterate over keys in the dictionary and extract the 6th element of the array. I tried the following; but did not meet with any luck:

for keys in dictKeyMutableDict {
    let xCentVal = xyz[keys as! [NSCopying]][6]
}

I keep on receiving a subscript error and if I remove as! [NSCopying], I receive the above error. Does anyone know how to deal with such case?


回答1:


Remove NSMutableDictionary and make it mutable by make it a var. Now you can remove the as! [NSCopying]

var xyz = ["1":[1,2,3,4,"1","n","1","2"],"2":[1,2,3,4,"+","o","6","2"]]

for keys in dictKeyMutableDict {
    let xCentVal = xyz[keys]![6]
}

Or better optional unwrap it:

for keys in dictKeyMutableDict {
    if let v = xyz[keys] {
        let xCentVal = v[6]
    }
}


来源:https://stackoverflow.com/questions/36583232/argument-type-anyobject-does-not-conform-to-expected-type-nscopying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!