Note

Codable

xnoag 2023. 2. 10. 02:12

Codable공식 문서에서는 다음과 같이 설명한다. 'A type that can convert itself into and out of an external representation. -> 자신을 변환하거나 외부 표현으로 변환할 수 있는 타입이다.' 주로 JSON 파일의 형태로 데이터를 주고 받는데, 공식 문서에서 설명하는 외부 표현은 JSON 파일의 형태라고 생각하면 된다. Codable Protocol을 사용하면, JSON을 손쉽게 다룰 수 있게 해준다.

 

공식 문서에서는 Codable을 Type Alias(타입 별칭) 형태로 정의하고 있다. Type Alias는 코드를 더 간결하고 가독성 있게 작성하기 위해 사용한다. 타입 별칭, 즉 별명을 새로 지어주는 것으로, 새로운 타입을 만드는 것은 아니다. 기존에 있는 타입을 새로운 이름으로 부를 수 있게 만들어주는 것 뿐이다. Type Alias는 기존에 있던 Protocol끼리의 결합, 기본 데이터 타입에 의미 추가 등에 사용되는데, Codable은 기존에 있던 Decodable Protocol과, Encodable Protocol끼리 결합시킨 Protocol이다. 

 

typealias Codable = Decodable & Encodable

 

Decodable공식 문서에서는 다음과 같이 설명한다. 'A type that can decode itself from an external representation. -> 외부 표현을 해석할 수 있는 타입이다.' Encodable공식 문서에서는 다음과 같이 설명한다. 'A type that can encode itself to an external representation. -> 외부 표현으로 암호화할 수 있는 타입이다.' 정리하면, Decodable은 외부에 암호화된 데이터를 해독할 수 있게 해주고, Encodable은 데이터를 암호화하여 외부에 내보낼 수 있게 해준다고 생각하면 된다. JSON 파일로 예를들면, Decodable은 JSON을 내가 원하는 모델로 Decode, Encodable은 모델을 JSON으로 Encode하게 해준다.

 

그럼 다시 Codable Protocol의 공식 문서 설명으로 돌아가보자. 'A type that can convert itself into and out of an external representation. -> 자신을 변환하거나 외부 표현을 변환할 수 있는 타입이다.' 자신을 변환하거나는 Encodable을 말하고, 외부 표현을 변환할은 Decodable을 말한다. 예를 들면, 

 

struct SomeStruct: Codable {}

 

Codable Protocol을 준수하는 SomeStruct 구조체는 데이터를 Decode, Encode 할 능력이 있다는 것을 의미한다.