Codable
Decodable
Encodable
Decodable
에 대해 알아보자. 공식 문서에 따르면, 외부 표현으로부터 자기 자신을 디코딩할 수 있는 타입이라고 한다.Encodable
은 공식 문서에 따르면, 외부 표현으로 자신을 인코딩할 수 있는 타입이다.Encodable
과 Decodable
은 앱이 외부와 데이터를 주고받기 위해 필수적인 프로토콜이다.Codable
은 뭐냐? 놀랍게도, Decodable
과 Encodable
을 함께 묶어서 칭하는 typealias
이다..Codable
을 적용하면 Decodable
과 Encodable
을 같이 적용한 것과 완전히 같다는 것이다.typealias
였을 줄이야.Codable
을 붙여줌으로써 간단히 외부와 통신할 수 있는 자료형을 만들 수 있다. CodingKey
를 통한 외부 표현과의 올바른 매칭이 필요할 수도 있지만..Codable
하게 만들려면, 타입 안에 들어가는 프로퍼티들이 전부 Codable
을 만족해야 한다.String
과 Int
등은 기본적으로 Codable
을 만족하기 때문에, 해당 속성의 프로퍼티로만 이루어진 타입은 바로 Codable
을 적용할 수 있다.Codable
하지 않은 프로퍼티나 타입 등을 Codable
하게 만들어 주기 위해 몇 가지 선택지가 있다.String
형식의 이미지 이름 프로퍼티와, 해당 프로퍼티를 기반으로 한 URL
을 사용해 이미지를 가져와 UIImage
를 반환하는 연산 프로퍼티를 가지고 있다는 것을 상상해보면 쉽다.struct Information: Codable {
let name: String
let imageName: String
var thumbnail: UIImage? {
let url = URL(String: Path.baseURL + imageName)
let data = Data(contentsOf: url!)
let image = UIImage(data: data)
return image
}
}
Codable
하지 않은 것을 이니셜라이저로 받아서 Codable
한 결과를 돌려주는 인스턴스.Codable
하게 만들고자 하는 타입에 extension
을 통해 Encodable
의 encode(to: Encoder) throws
메서드와, Decodable
의 init?(from: Decoder) throws
이니셜라이저를 구현해도 되겠다.https://developer.apple.com/documentation/swift/encodable
https://developer.apple.com/documentation/swift/decodable
https://developer.apple.com/documentation/swift/codable
https://developer.apple.com/documentation/foundation/url/3126806-init
https://stackoverflow.com/questions/46197785/how-to-conform-uiimage-to-codable