Codable
Codable 이란?

자신을 외부 표현으로 또는 외부 표현으로 변환할 수 있는 형식입니다.
Apple Developer에서는 Codable을 위와 같이 설명한다.
여기서 외부 표현(External Representation)의 좋은 예로 JSON 형태의 파일이 있을 수 있다.
Codable = Decodable & Encodable
추가로 위와 같이 정의 되어있는데, Decodable과 Encodable은 각각 디코딩 할 수 있는 타입, 인코딩 할 수 있는 타입을 의미하는 프로토콜이다.
따라서 Codable은 외부표현으로 디코딩하거나 인코딩할 수 있는 프로토콜이라는 뜻이다.
Codable을 이용한 디코딩, 인코딩 예제를 살펴보자.
Encoding Example
import UIKit
struct Car: Codable{
var name: String
var price: Int
}
let encoder = JSONEncoder()
let Avante = Car(name: "Avante", price: 2000)
let jsonData = try? encoder.encode(Avante)
if let jsonData = jsonData, let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
위 코드를 실행시 아래와 같은 결과가 잘 나오는 것을 확인할 수 있다.
주석을 확인해보면 어려운 코드가 아니라 쉽게 이해할 수 있다.
{"name":"Avante","price":2000}
Decoding Example
let decoder = JSONDecoder()
if let jsonData = jsonData, let carData = try? decoder.decode(Car.self, from: jsonData) {
print(carData.name)
print(carData.price)
}
jsonData는 Encoding Example에서 사용된 것을 그대로 사용했다.
encode, decode 모두 실패할 경우 에러를 발생시킬 수 있으므로 try와 함께 써줘야한다.
참고자료