Swift Codable Decode Manually Optional Variable
In my model, what I did is
var title: String?
...
title = try container.decode(String?.self, forKey: .age)
rather than
name = try? container.decode(String.self, forKey: .age)
For example for some reason backend passes a numeric value for that key, like title: 74
. With the 1st method, you will get error message like this (I wrote a unit test for my model), and you can pinpoint the problem quickly
However, With the 2nd method try?
, this useful error message will be silenced and will not bubble up. You will still get a valid decoding result title = nil
, which actually is not true in most cases, if only null
from backend is supposed to yield a nil
.
But of course, if you design is that no matter what is retrieved from backend, as long as the type does not match, it will be a nil
. Then I think there shouldn't be any problem with the 1st method.
Age is optional:
let age: String?
So try to decode in this way:
let age: String? = try values.decodeIfPresent(String.self, forKey: .age)