在init中模糊地使用下标

时间:2016-06-13 17:59:39

标签: swift

我刚从http://openweathermap.org/api创建的新对象天气中遇到init问题。我的项目在Xcode中与模拟器配合得很好,但是当我想将我的应用程序放在我的智能手机中时,我只会遇到一个致命的问题。 当它构建时,它表示我对下标进行了不明确的使用。

以下是我在教程中使用的代码部分:

init(weatherData: [String: AnyObject]) {

    city = weatherData["name"] as! String

    let coordDict = weatherData["coord"] as! [String: AnyObject]
    longitude = coordDict["lon"] as! Double
    latitude = coordDict["lat"] as! Double

    let weatherDict = weatherData["weather"]![0] as! [String: AnyObject] // Error came here.
    weatherID = weatherDict["id"] as! Int
    mainWeather = weatherDict["main"] as! String
    weatherDescription = weatherDict["description"] as! String
    weatherIconID = weatherDict["icon"] as! String

    let mainDict = weatherData["main"] as! [String: AnyObject]
    temp = mainDict["temp"] as! Double
    humidity = mainDict["humidity"] as! Int
    pressure = mainDict["pressure"] as! Int

    cloudCover = weatherData["clouds"]!["all"] as! Int

    let windDict = weatherData["wind"] as! [String: AnyObject]
    windSpeed = windDict["speed"] as! Double
    windDirection = windDict["deg"] as? Double

    if weatherData["rain"] != nil {
        let rainDict = weatherData["rain"] as! [String: AnyObject]
        rainfallInLast3Hours = rainDict["3h"] as? Double
    }
    else {
        rainfallInLast3Hours = nil
    }

    let sysDict = weatherData["sys"] as! [String: AnyObject]
    country = sysDict["country"] as! String
    sunrise = NSDate(timeIntervalSince1970: sysDict["sunrise"] as! NSTimeInterval)
    sunset = NSDate(timeIntervalSince1970:sysDict["sunset"] as! NSTimeInterval)
}

此代码从天气API导入的Dict中提取值。

知道解决方案吗?

感谢所有人。

1 个答案:

答案 0 :(得分:2)

再做一步,将weather的类型指定为字典数组

let weather = weatherData["weather"] as! [[String: AnyObject]]
let weatherDict = weather[0]

因为编译器并不确切知道weather是否是数组(索引下标)或字典(密钥下标)。这是模棱两可的。

PS:更好的语法(除了所有强制解包的选项之外)是

if let rainDict = weatherData["rain"] as? [String: AnyObject] {
    rainfallInLast3Hours = rainDict["3h"] as? Double
} else {
    rainfallInLast3Hours = nil
}