简体   繁体   中英

Ambiguous use of 'subscript' after converting to swift 2.3

I got this Errors after I converting to 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
                }

The Ambiguous use of subscript error comes by declaring "loadedWeather, loadedTemperatur and loadedWindSpeed".

Already tried to change NSDictionary to Dictionary and other things, helped on another position in code, but here....

thanks guys

This happens because compiler doesn't know what are the intermediary object is in each of your line ... so may be

   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 

I think that the issue is that the compiler cannot work out what json["weather"] is, You may need to be more specific in your code.

Try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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