ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • decode vs decodeIfPresent
    iOS 2022. 12. 14. 16:01
    반응형

    Codable 이후 필드명이나 코딩키만으로 직접 디코딩없이 파싱이 가능해졌지만,
    그럼에도 별도의 처리가 필요하다면 여전히 디코더를 통한 생성자를 만들어줘야 할 때가 있습니다.

    이때 필요한 decode 와 decodeIfPresent 의 차이는 "해당 필드가 존재하냐" 의 여부로 관점으로 생각해볼 수 있습니다.

    다음 JSON 을 파싱하려고 할 때,

    {
      title: "woongs",
      subtitle: "decoding"
    }

     

    다음과 같이 만들어볼 수 있습니다. 아직 딱히 문제는 없습니다.

    required init(from: decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.title = try container.decode(String.self, forKey: .title)
        self.subtitle = try container.decode(String.self, forKey: .subtitle)
    }

     

    하지만 만약 아래와 같이 title만 있다면 위 코드는 에러가 발생합니다.
    subtitle 필드가 아예 없기 때문이죠.

    {
      title: "woongs"
    }

    위와 같은 JSON 을 파싱하고자 할 때 아래와 같이 decodeIfPresent 를 사용할 수 있습니다.
    해당 필드가 있을 경우만 decode 하고 없다면 nil을 반환합니다.

    required init(from: decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.title = try container.decode(String.self, forKey: .title)
        ✅ self.subtitle = try container.decodeIfPresent(String.self, forKey: .subtitle)
    }

     

     

     

     

    반응형

    댓글

Designed by Tistory.