728x90
안녕하세요.
JSON을 Decoding 할 때 enum associated value도 잘 될까? 하는 의문이 있어서 직접 해봤습니다ㅋㅋ
결론은 key 값만 잘 맞추면 잘 되는 것 같아요! 갓스위프트
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct User: Codable { | |
let userID: String | |
} | |
enum Response: Codable { | |
case success(user: User) | |
case fail(message: String, code: Int) | |
} | |
let jsonString1 = """ | |
{ | |
"success" : { | |
"user" : { | |
"userID" : "AAAA" | |
} | |
} | |
} | |
""" | |
let response1 = try JSONDecoder().decode(Response.self, from: jsonString1.data(using: .utf8)!) | |
print(response1) // success(user: __lldb_expr_13.User(userID: "AAAA")) | |
let jsonString2 = """ | |
{ | |
"fail" : { | |
"message" : "something wrong", | |
"code" : -999 | |
} | |
} | |
""" | |
let response2 = try JSONDecoder().decode(Response.self, from: jsonString2.data(using: .utf8)!) | |
print(response2) // fail(message: "something wrong", code: -999) |
이번 글은 여기서 마무리.
반응형
'Swift' 카테고리의 다른 글
Designated initializer cannot be declared in an extension (0) | 2024.12.29 |
---|---|
map, compactMap, flatMap (0) | 2024.08.18 |
lazy var 클로저에서 retain cycle이 생기는 경우 (0) | 2024.06.20 |
@propertywrapper (0) | 2024.06.07 |
protocol initializer가 클래스에서 required로 정의되어야 하는 이유 (0) | 2024.05.12 |