Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Created May 17, 2022 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TuenTuenna/0a5058abe279b4451db79027ae429c82 to your computer and use it in GitHub Desktop.
Save TuenTuenna/0a5058abe279b4451db79027ae429c82 to your computer and use it in GitHub Desktop.
swift_multi_key_decoding
struct Person: Decodable {
    var name: String

    // 멀티 키에 대한 디코딩
    enum CodingKeys: String, CodingKey, CaseIterable {
        case name, realname, nickname
    }

    init(from decoder: Decoder) throws {
        
        let container = try decoder.container(keyedBy: CodingKeys.self)
        // 코딩키들 가지고 있으면 디코딩하기
        // name, realname, nickname
        if let key = container.allKeys.filter({ CodingKeys.allCases.contains($0) }).first,
           let value = try container.decodeIfPresent(String.self, forKey: key) {
            self.name = value
        } else {
            self.name = ""
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment