Reputation: 21
I'd just get an issue with a init in a new object Weather I created from http://openweathermap.org/api. My project worked well with a simulator in Xcode but when I wanted to put my application in my smartphone, I just get a fatal issue. When it built, it says that I made a Ambiguous use of subscript.
Here is the part of the code I used from a tutorial :
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)
}
This code extract values from a Dict imported from the weather API.
Have any idea of a solution ?
Thank for all.
Upvotes: 0
Views: 155
Reputation: 285150
Do one more step to specify the type of weather
as an array of dictionaries
let weather = weatherData["weather"] as! [[String: AnyObject]]
let weatherDict = weather[0]
because the compiler does not exactly know if weather
is an array (index subscripted) or dictionary (key subscripted). That's the ambiguity.
PS: A better syntax (aside from all forced unwrapped optionals) is
if let rainDict = weatherData["rain"] as? [String: AnyObject] {
rainfallInLast3Hours = rainDict["3h"] as? Double
} else {
rainfallInLast3Hours = nil
}
Upvotes: 2