Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

ios - Ambiguous use of subscript xcode 7.1

I have this code:

var jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
var count = jsonResult["levels"]!.count as Int
for var i=0; i<count; ++i {
   let obj = jsonResult["levels"]![i] as! NSDictionary
   ...
}

On the last line I am receiving this error:

Ambiguous use of subscript

How can I resolve this?

This code has worked for some time but with the upgrade to xcode 7.1 it broke and stopped working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to tell the compiler what the intermediary object is in the line

let obj = jsonResult["levels"]![i] as! NSDictionary

After the statement jsonResult["levels"]! the compiler does not know what kind of object he is dealing with. You have to tell it that is an NSArray or something else:

let obj = (jsonResult["levels"] as! NSArray)[i] as! NSDictionary

Of course you should additionally make sure that you can actually do all that casting and that the objects inside the json are really of the expected type.


Even a little bit shorter using only one cast by directly casting to an array of NSDictionary:

let obj = (jsonResult["levels"] as! [NSDictionary])[i]

The reasoning remains the same: you tell the compiler of what type jsonResult["levels"]. It is supposed to be an array containing NSDictionarys.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...