TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Day 49 - itunes json decoding example - how did it work!?!

Forums > 100 Days of SwiftUI

Posting here for the first time because I'm having a "how the heck did that work?" moment.

In the Day 49 video "Sending and receiving Codable data with URLSession and SwiftUI" Paul downloads a Taylor Swift track lisy from itunes populating it into a results array capturing these basic fields:

struct Result: Codable { var trackId: Int var trackName: String var collectionName: String }

I took a look at the Apple API description and raw json that is returned from this search and it is WAY more complicated than these three simple fields, there is a lot of other data. So how did it decode? Why isn't there an error? I know it works bevause I have tired the example code but I don't understand why.

If the decoder is so clever that it can just pick out the few pieces of information that you have asked for in the mass of json is this always the case or are there limits?

Apologies in advance if I'm asking the dumbest question in the world.

Thanks, Gairn

2      

Hi Gairn! There are some rules that you have to follow so that JSON data will be decoded correctly. But to the point of your question, you are correct, you can cherry pick the data that you need for you purpose. Other pieces will be ingnored. The data sent to you, you get all data in JSON format, you say: "Ok, i need only this, that and so on... the rest I don't care". Then the decoder provided by Swift will handle data, and accordging to structure you provided and place it inside the instance. And you have object ready for other work that you wanted to do with that.

JSONDecoder().decode([TypeYouNeedToUse], from: dataThatWasSentToYou)

2      

Many thanks @ygeras. I did a bit more playing with the example from the video cherry picking some other items out of the json so my understanding is increasing (albeit slowly).

I have to say I love SwiftUI, it does so much for you - even if the underlying principles are the same it is significantly easier to get things done than it was 30 years ago when I first learnt to code!!

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.