Let’s assume that you’re doing an application which shows your users pretty pictures of seasons. You contact your backend folks and they tell you that the world is simple, there are only three seasons:
1 2 3
In order to compose things nicely, you put the seasons into a struct:
1 2 3
The following JSON comes from the server, it gets decoded, everything works well:
The application gets released. Time passes, winter comes and the app gets updated available seasons from the backend:
What happens now? Your functionality breaks.
Since the app can’t understand
Season.winter, no seasons get decoded. You receive a lot of bug reports, and your users are not happy ☹️
If only there was something we could do to prevent this from happening..
This seems like a nice use case for property wrappers!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
This way, we simply add
@IgnoreUnknown before our available seasons and voilà! After that, the
available array simply skips the values it cannot understand 🚀
1 2 3 4
Property Wrappers come with a lot of other great use cases. Please see Properties in Apple documentation for more details 🙂
Hope this blogpost was helpful, thanks for reading!