If you like my content, visit my website for more.
If you’ve been working with Apple’s Decodable
protocol, you may figure out that we cannot treat any other things as String
when parsing JSON. Suppose that our backend decides that long int
is cool for an ID field. However, you know deep down that sooner or later, they will shift to using String
instead of long int
for ID. And it is irritating to write custom logic for a whole Decodable
object when there is only 1 field that cannot be parsed naturally.
Thus, it is worth it to invest some time to write a thin wrapper around String
to help its decoding more easily. The idea is to create a new class which contains only a String
property. Then, we sequentially try to parse it as Double
, UInt64
, Int64
, and finally as String
. You can try to throw in as many other type of data types as you see fit. I personally am satisfied with these 3 types.
Below is some simple test cases I wrote to test that our new class DecodableString
can perform what it promises.
And the test results:
Additionally, we can put tests to assert that our DecodableString
throws exception if we didn’t give them Number
or String
(such as Bool
, or a nested JSON structure). However, I think those tests are unnecessary, so let’s call this a day.
Happy Coding!