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
LinkedIn Twitter Instagram Original Blog Github HackerRank
Photo by CHUTTERSNAP on Unsplash
Originally published at https://alexalmostengineer.co.ua on January 25, 2021.