“下标的不明确使用"新的Swift更新后出现错误 [英] "Ambiguous use of subscript" Error after new Swift update

查看:112
本文介绍了“下标的不明确使用"新的Swift更新后出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目之前运行良好,但如果使用模拟器,则仍可以正常运行.但是,当我连接iPhone并尝试运行项目时,出现以下错误:在此行上检索JSON信息时出现下标用法不正确":

My project was running fine before and still runs fine if using the simulator. But when I connect an iPhone and try and run the project I get this error: "Ambiguous use of subscript" when retrieving JSON info on this line:

 let channels = jsonResult["channels"]?[0] as? [String: AnyObject]

感谢您提供任何补救措施!

Any help to remedy this is appreciated!

推荐答案

编译器似乎对类型的限制更大.

The compiler seems to be more type restrictive.

jsonResult["channels"]的结果类型是AnyObject,您必须通过检查作为数组的值来帮助编译器.

The result type of jsonResult["channels"] is AnyObject you have to help the compiler by checking the value for being an array.

if let channels = jsonResult["channels"] as? [AnyObject], channel = channels[0] as? [String: AnyObject] {
  // do something with channel
}

或更安全地检查数组是否不为空

Or still safer to check also whether the array is not empty

if let channels = jsonResult["channels"] as? [[String:AnyObject]] where !channels.isEmpty {
   let channel = channels[0] // now the compiler knows it's [String:AnyObject]
   // do something with channel
}

这篇关于“下标的不明确使用"新的Swift更新后出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆