[iOS] 커스텀 데이터 타입 Codable하게 만들기

Chae-young Park·2023년 10월 6일

프로젝트를 하던 중 커스텀 데이터 타입을 파이어베이스에 저장하기 위해 인코딩이 필요한 상황이 생겼다.

Encoding and Decoding Custom Types에 자세히 나와있듯이 커스텀 데이터 타입이 Encodable, Decodable 프로토콜을 따르도록 작성하면 Encoder, Decoder 프로토콜이 데이터를 자동으로 encode, decode 해준다고 한다.

이때, 인코딩과 디코딩을 모두 지원하기 위해 Encodable, Decodable 프로토콜을 합친 Codable 프로토콜을 활용할 수 있는데, Codable한 커스텀 데이터 타입으로 이루어진 또다른 커스텀 데이터 타입 역시 Codable하다고 한다.

struct Coordinate: Codable {
    var latitude: Double
    var longitude: Double
}


struct Landmark: Codable {
    var name: String
    var foundingYear: Int
    
    var location: Coordinate
}

공식 문서에서 발췌한 위 코드를 보면 Landmark 구조체는 커스텀 데이터 타입인 Coordinate 타입의 location 프로퍼티를 가지고 있다. Landmark 구조체가 Codable 프로토콜을 준수하기 위해서는 Coordinate 타입도 Codable하면 된다.

따라서 Coordinate 구조체에서 각각 latitude와 longitude를 본래 Codable한 타입인 Double로 정의하고, Coordinate 구조체에 Codable 프로토콜을 적용시키면 Landmark 구조체 역시 Codable하게 된다.

profile
iOS developer

0개의 댓글