Predict the output
What happens when this decodes?
struct User: Decodable {
let userName: String
enum CodingKeys: String, CodingKey { case userName = "user_name" }
}
let json = #"{"user_name": "ana"}"#.data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let user = try decoder.decode(User.self, from: json)Hint 1 of 1
Which runs first: the key strategy or the CodingKeys match?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B It throws keyNotFound
Correct. Use either the strategy or the custom CodingKeys, not both.
Why not the others?
- A It decodes "ana". The strategy has already renamed the key to userName, which doesn't match "user_name".
- C userName becomes an empty string. Decoding never invents default values.
- D It doesn't compile. The code compiles; the failure happens at runtime.