As I’ve written before I am very keen on getting web service results out of JSON and into a strongly typed form as soon as possible. It makes the rest of your code much cleaner, insulates you from knowledge of the web service keys and format and aids testing.
Swift structs are a natural home for your web service results - they are immutable, lightweight and have minimal boilerplate code requirements. Getting the results out of JSON and into a struct, however, can be complicated - verifying the correctness of each key in the JSON can quickly lead to an
if let staircase of doom.
I wanted to use something clever and functional, but this has readability drawbacks (I’m not yet comfortable with scattering custom operators all over the place) and also requires me to write a curried initializer for each struct, which seemed like repeating myself a bit too much.
My design goals were:
- Minimise repetition of code and boilerplate
- Allow for flexibility if the API changes
- Allow for optional properties
- Take advantage of compile-time checking
- Feel at least slightly like I had done something a bit “Swifty”
Here’s what I came up with.