[iOS] Parsing (many things) as String

Bach Le
2 min readFeb 24, 2020

--

If you like my content, visit my website for more.

Chill morning reading and writing

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:

Test run result for DecodableString

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!

--

--

Bach Le

iOS Developer with humble experience. Medium is where I read a lot, I say thanks by beginning to write stories.