상세 컨텐츠

본문 제목

Guide to Swift Codable. Chapter 3: Taking the Controls

TIL/Swift Codable

by box-jeon 2018. 4. 30. 22:11

본문

역시 고수들은 언제나 길을 찾아내는군요. 절 좌절시켰던 몇몇 상황들을 멋지게 풀어내고 있습니다. 정 안되면 그냥 JSONSerialization을 쓰라며 겸손한 마무리까지...


- Decoding Unknown Keys

Key가 런타임에 결정되는 경우, enum을 사용할 수가 없습니다. CodingKey를 conform하는 struct를 정의한 후, 객체를 생성해서 decode key로 넘기는 방법을 사용합니다.



- Decoding Indeterminate Types

type key를 가지며, type에 따라 다른 구조를 갖는 경우입니다. type에 맞춰 enum을 정의한 후, associated value에 각각의 객체를 담아서 처리합니다.



- Decoding Arbitrary Types

metadata나 userInfo 같은 property를 추가해서 열린(?) 구조로 객체를 디자인하는 방법입니다. 하지만 Any는 Codable을 conform하고 있지 않고, generic은 concrete type만 허용하기 때문에 [String: Codable]도 사용할 수 없습니다. 이를 해결하기 위해 Codable을 conform 하는 wrapper structure로 AnyCodable을 작성하였습니다. 아이디어도, 구현도 너무나 훌륭합니다(https://github.com/Flight-School/AnyCodable).


- Decoding Multiple Representations

Data source가 여러 군데여서 data provider 마다 format이 조금씩 다른 경우입니다. 공통 인터페이스를 protocol로 추출한 후, 각각의 struct/class가 그를 conform하는 방법을 사용합니다. 혹은 api 개발자와 말로 풀어보는 것도 괜찮을 것 같습니다.


- Decoding Inherited Types

Decodable을 conform한 class를 상속할 경우, subclass는 init(from:)를 반드시 구현하고 새로 추가된 property들을 명시적으로 decode해야합니다. init(from:) 외에도 designated initializer가 있다면 그것도 별 수 없이 override 해줘야하겠지요.



- Decoding from Different Types of Values

이쯤 오면 거의 만능키가 필요해집니다. api 개발자를 만납시다. decoder.container(keyedBy:), decoder.unkeyedContainer(), decoder.singleValueContainer()를 이용해 dictionary, array, single value를 각각 처리할 수 있습니다.



- Configuring How Encodable Types Are Represented

JSONDecoder에서 dateDecodingStrategy를 사용한 것과 유사하게 custom encoding strategy를 JSONEncoder에게 넘기는 것이 가능합니다. 정확히 말하면, encoding strategy 기능을 제공하고 있는 것이 아니라 JSONEncoder의 userInfo property를 이용해서 dateDecodingStrategy를 흉내내고 있습니다.


관련글 더보기

댓글 영역