简体   繁体   English

新 Swift 更新后出现“下标使用不明确”错误

[英]"Ambiguous use of subscript" Error after new Swift update

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:但是,当我连接 iPhone 并尝试运行该项目时,在此行上检索 JSON 信息时出现此错误:“下标的使用不明确”:

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

Any help to remedy this is appreciated!任何解决此问题的帮助表示赞赏!

The compiler seems to be more type restrictive.编译器似乎更受类型限制。

The result type of jsonResult["channels"] is AnyObject you have to help the compiler by checking the value for being an array. jsonResult["channels"]的结果类型是AnyObject您必须通过检查数组的值来帮助编译器。

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
}

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

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