Decoding JSON with endless nesting in Swift. Recursion in use
Hi, this is a #FastTip about decoding JSON with endless nesting. I found this question in the iOS devs community and decide to help. Hope it will be useful!
For decoding, we will use the Decoding protocol from Standard Swift Library
As you can see, the JSON can have every level of nesting as you need. For testing and applying for the work with endless process of anything, it is super useful to know about recursion.
A little trick here, that struct Object has parameter “sub_elements” with type Optional(Array of Objects). That’s how any Object can have other Objects in these parameters and these objects can have other objects and so on.
Another urgent part here is a type of “sub_elements” — this is Optional Array. By this Optional type, we can easily check that this is the last level of nesting. You can see that in showElements function.
In the showElements function, you can also see a recursion example when showElements will call another showElements while all levels will be printed.
Result of calling showElements will be:
— Item 6ECF5DA1–0558–436C-93E7-CCED4461866D Group
— — Item 4412C2FA-47D3–4524-A054-F06AE843DA45 Group 2
— — — Item 4315FAC2–0809–478C-BED8–54F28B0A9A57 Shape 1
— — — Item D2985D5B-B98A-4549-A4ED-3742583A2532 Image 1
— — — Item C67F6AE9–2EA5–4850-AA00–2A1DB8EB4167 Group 3
— — — — Item 718F235A-E2FB-4A05-A2A9–198CFA6B135A Shape 2
— — — — Item 0C232502-A0D6–4BC7-B4DD-178B0BFE8BB0 Image 2
— — Item 99BBAA31–0A9D-46F8–89C7-BD7EE444919E Shape
— — Item B5281F95–72A4–4973–9A70–18ABF1D3DD92 Image
My social media
Originally published at https://alexalmostengineer.co.ua on January 25, 2021.