【问题标题】:Ambiguous use of 'subscript' after converting to swift 2.3转换为 swift 2.3 后模糊使用“下标”
【发布时间】:2016-09-13 09:32:16
【问题描述】:

我在转换为 swift 2.3 后出现此错误。

guard let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary else {
                    throw JSONError.ConversionFailed
                }

                guard
                    let loadedWeather = json["weather"]![0]["description"] as? String,
                    let loadedTemperatur = json["main"]!["temp"] as? Float,
                    let loadedWindSpeed = json["wind"]!["speed"] as? Float
                    else {
                        print("Weather JSON-Parsing failed")
                        return
                }

Ambiguous use of subscript 错误来自声明“loadedWeather、loadedTemperatur 和 loadedWindSpeed”。

已经尝试将 NSDictionary 更改为 Dictionary 和其他东西,帮助了代码中的另一个位置,但是在这里....

谢谢大家

【问题讨论】:

    标签: ios json swift dictionary


    【解决方案1】:

    发生这种情况是因为编译器不知道你的每一行中的中间对象是什么......所以可能是

       if let weather = json["weather"] as? [[String:String]], firstObject = weather.first as? [String:String]{
            let loadedWeather = firstObject["description"]
       }
    
       // same for other objects i.e. `json["main"]` and `json["wind"]` with its return type 
    

    【讨论】:

      【解决方案2】:

      我认为问题在于编译器无法计算出json["weather"] 是什么,您可能需要在代码中更具体。

      试试

      let loadedWeather = (json["weather"] as! [[String:AnyObject]])[0]["description"] as? String
      

      【讨论】:

      • 谢谢你们!你们俩都解决了我的问题,我决定采用这个解决方案。
      猜你喜欢
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      相关资源
      最近更新 更多