In the last tutorial we’ve seen how to use functional concepts to parse JSON into Swift models. One of the main problems with that code is it doesn’t support value transformations, ie., changing the values coming from JSON before assigning them to the model. Let’s try to implement it.
Posts in this series:
As you can see, the
is_married flag from JSON is either
m depending on whether the
Person is married or not. These strings need to be mapped into
Bool before assigning them to our
parseIsMarried does this mapping for us:
For applying this transformation method, let’s define one more operator that has a higher precedence than
This newly defined operator can be used as follows:
The way it works is:
getfunction will retrieve the
is_marriedvalue from JSON as a
- This value is passed to
<~~is having higher precedence than
- The transformation function then maps the value to appropriate boolean value
- This mapped value will then be passed to our curried function.
Using this transformation operator, we can even map nested objects as well.
The whole source code (along with more usecases for transformation) can be found in this gist