I was creating a weather forecasting app for learning purpose with API. The API has the Jason formatted data given below:
{
"coord": {
"lon": 139,
"lat": 35
},
"weather": [
{
"id": 520,
"main": "Rain",
"description": "light intensity shower rain",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 293.15,
"pressure": 1005,
"humidity": 94,
"temp_min": 293.15,
"temp_max": 293.15
},
"visibility": 10000,
"wind": {
"speed": 7.2,
"deg": 210
},
"clouds": {
"all": 75
},
"dt": 1527753600,
"sys": {
"type": 1,
"id": 7616,
"message": 0.0068,
"country": "JP",
"sunrise": 1527708700,
"sunset": 1527760320
},
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
I wanted to access the weather dictionary and tried to access the main key value with this line of codes in the latest version of swift.
I can get the city name and the temperature But when i implement these codes I always have erorr warnings and can not access the main in the weather.
Can anyone has any idea how to resolve this problem?
if let dict = result.value as? Dictionary< String, AnyObject>{
if let name = dict["name"] as? String {
self._cityName = name
}
if let weather = dict["weather"] as? Dictionary<String,AnyObject >{
if let main = weather[0]["main"] as? String {
self._weatherType = main
}
}
if let main = dict["main"] as? Dictionary<String, AnyObject>{
if let currentTemp = main["temp"] as? Double {
let kelvinToFarenheitPre = (currentTemp * (9/5) - 459.67)
let kelvinToFarenheit = Double( round(10 * kelvinToFarenheitPre/10 ))
self._currentTemp = kelvinToFarenheit
}
}
//print(self.cityName)
}
//print("\(dict)")
print(self.weatherType)
print(self.cityName)
}
In this case the problem is with the code. For this specific case there is no change in swift 3 and swift 4.1
I was referring it only a dictionary but in json it is an array of dictionary so I need to cast is as the array of dictionary.
So, for this the correct code would be:
if let weather = dict["weather"] as? [Dictionary<String,AnyObject >]{
if let main = weather[0]["main"] as? String {
self._weatherType = main
}
}