簡體   English   中英

轉換為Swift 2.3后對“下標”的模棱兩可使用

[英]Ambiguous use of 'subscript' after converting to swift 2.3

轉換為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錯誤的Ambiguous use of subscript是通過聲明“ loadedWeather,loadedTemperatur和loadedWindSpeed”來實現的。

已經嘗試將NSDictionary更改為Dictionary等,在代碼的另一個位置有所幫助,但是在這里。

多謝你們

發生這種情況是因為編譯器不知道每行中的中間對象是什么...所以可能是

   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 

我認為問題在於編譯器無法計算出json["weather"]是什么,您可能需要在代碼中更加具體。

嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM