简体   繁体   English

下标xcode 7.1的使用不明确

[英]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. 这段代码已经工作了一段时间,但是随着xcode 7.1的升级,它中断了并停止了工作。

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"]! 在声明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: 您必须告诉它是NSArray或其他东西:

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. 当然,您还应该确保可以进行所有强制转换,并且json中的对象确实属于预期类型。


Even a little bit shorter using only one cast by directly casting to an array of NSDictionary : 通过直接转换为NSDictionary数组,仅使用一个转换就可以缩短一点时间:

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

The reasoning remains the same: you tell the compiler of what type jsonResult["levels"] . 推理保持不变:您告诉编译器jsonResult["levels"]是什么类型。 It is supposed to be an array containing NSDictionary s. 应该是包含NSDictionary的数组。

In the new Swift update. 在新的Swift更新中。 You should get your value with objectForKey("yourKey") method rather than ["yourKey"] . 您应该使用objectForKey("yourKey")方法而不是["yourKey"] In your case, 就你而言

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM