개발/iOS
codable
kwony
2020. 11. 23. 15:49
codable은 swift4에서 추가된 프로토콜로 JSON 처리를 손쉽게 해준다. 예로 서버로부터 이런 json 결과물을 받으면
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 4.91,
"feels_like": 1.93,
"temp_min": 4.44,
"temp_max": 6,
"pressure": 1028,
"humidity": 87
},
"visibility": 2800,
"wind": {
"speed": 2.1,
"deg": 230
},
"clouds": {
"all": 71
},
"dt": 1606106846,
"sys": {
"type": 1,
"id": 1414,
"country": "GB",
"sunrise": 1606116755,
"sunset": 1606147310
},
"timezone": 0,
"id": 2643743,
"name": "London",
"cod": 200
}
Codable과 Struct을 조합해서 필요한 값들을 추출해줄 수 있다. JSON 값의 key와 데이터 타입만 일치하면 받아오는데는 문제 없다.
struct WeatherData: Codable {
let name: String
let main: Main
let weather: [Weather]
}
struct Main: Codable {
let temp: Double
}
struct Weather: Codable {
let id: Int
let description: String
}
////
func parseJSON(_ weatherData: Data) -> WeatherModel? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
let id = decodedData.weather[0].id
let temp = decodedData.main.temp
let name = decodedData.name
let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
return weather
} catch {
delegate?.didFailWithError(error)
return nil
}
}