Codable in Swift 5: What is it & how to use? (Xcode 11, 2020) - iOS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what is he on guys welcome back to another Swift video in today's video we're gonna be going over the Kota bullet protocol a little bit in depth I've definitely gone over this before but I think it deserves a focused video plus you guys have been asking for it so here we have a URL pulled up for some random API that returns sunrise and sunset times and we're gonna be using the return JSON and this in our code bullet example so that's it make sure you absolutely destroy that like button down below for the YouTube algorithm make sure you hit subscribe while you're at it if you're new to the channel get excited getting suka ready and let's jump right in quick pause before we get into the video if you haven't seen it already I am hard at work putting together iOS Academy io a community where all of us iOS engineers can come together learn how to build some of the top apps like Facebook YouTube and Instagram in addition to interview prep to learn some of these iOS roles at top tech companies so if you're interested in the free and premium content to come head on over to iOS Academy IO and enter your email address into the wait list forum and you will be notified as content becomes available that said let's get into the video all right so guys Xcode opened up here let's see if we can get away with this video in a playground so I'm gonna create a playground we can stick with the blank template and I'm gonna go ahead and call this codable instead of using those default names I feel like I always use those and I ends up with a million switz playground files so cool so let me expand this window that's give ourselves a little more room to work and let's talk about codable so to talk about codable I think a little bit of background is helpful so over here we still have the page open where we have this JSON coming back so codable is a protocol that allows us as developers to take bytes that are returned in the JSON format give it to a JSON decoder object and we can supply a structure class that conforms to this codable thing that we keep talking about and if that class has the proper types and property names and they match up with the JSON here the actual one-to-one mapping of the data and JSON here is done for us so it sounds pretty simple and it is but I think the the thing that folks that are starting off with iOS and codable more recent years don't appreciate is back in the day before Swift was a thing and even now with objective-c but you get JSON data you really have to do a lot of things like checking the type and checking if things are not nil whereas with codable all of it is handled for you magically so that's a bit of context behind it let's actually implement this so I'm gonna go ahead and copy this URL that I pasted it in here like it said it's returning sunrise and sunset times I think this is all in UTC time zone wise the contents are irrelevant so long as we get data back feel free to use this URL as well and we basically want to perform an API call to get the actual data out so we're gonna create a function and we're gonna say get data and we're gonna create a URL string and I'm gonna go ahead and just paste that string in here you can see that we provide latitude and longitude we also provide a date this is the I guess time zone or rather this is the sunset time it's gonna return for August 8th or August first rather so we have a URL here we then need to create a URL object from the string so that if created as an optional so we're gonna open this constructor up the name guard I'm gonna paste this guy in and if we're not able to create a string out of it we're just gonna return and then after that we can create a data task and a data task is how we perform actual API calls and networking tasks and we're gonna do data tasks with a URL and a completion so the URL will be our URL and the completion as you can see where the signature here returns three optional parameters so data URL response and error we only care about the data and the error so we're gonna do underscore for discardable for the second parameter now in here we're gonna say we're gonna make sure the data is not nil it's the data equals data and we want to make sure error is new make sure we didn't hit an error so like every time I say error it sounds weird in these videos but anyways if if we don't have data or we do hit a issue or an error we're gonna return out of it and I'm gonna put in here a print starting or though let's just say got data I want to print out the data and we can print out the data like so and then we can call task dot resume and that will actually kick off this API call this task and it'll get started resume is a misleading term I've actually filed the DTS with Apple like a bug report or rather a suggestion that they should change the name for this because it's super misleading in a lot of ways but anyways let's go ahead and run this whoops we don't want to open that we're gonna pull up this console here and I'm gonna go ahead and press this Run button and just kidding we should probably call this function that would be a fantastic idea so let me pause this down here let's call this function and let's hit run one more time and we should get a bunch of things printed out here rather instead of a bunch of things are one thing so we're definitely getting data back and the size of the data that we're getting back is 482 bytes but that's not that useful right like we want to get the data out of this so here's where codebook comes in so I'm gonna copy the expected response and I'm gonna come down here and we're gonna paste that in here in a comment now basically and close as a bottom thing we want to create a object that is conforming to the codable called that has the same keys and we need to make sure its type rather case sensitive and the types are properly accounted for so let's do that so the first thing you want to do is create a struct and we'll call it call it API response we'll make it codable and the top level of keys in this json let's return looks to be results and status we're not going to use any of these as the top level keys because they're all sub of the thing the result is pointing to so we need two keys in here results and then we also need a status okay so what if what are the types now so it looks like status is a string so we're gonna put string here and results actually points to another dictionary annotated by the fact that there's keys and values in here and we have these curly braces so what we need to do is create another object and I'm gonna call it API response results and this will be another struct I'll make sure this one is codable as well and now we want all of these in here so I'm gonna be lazy and copy and paste it it looks like all the values are strings except for this guy right here for day length so we'll deal with that one in a second so go ahead and paste that in here and we're gonna hold down option and you can multi-line select and it gives you multiple cursors to protip and we're gonna replace it with let and we can go ahead and delete all the stuff on the side so I guess we're gonna have to do this line by line but go ahead and say that its elite that these are all string so actually while you're deleting you can go ahead and throw out the type in there as well or even delete that be very careful that you're not deleting the actual part of the key I've done that before and wasted a lot of time trying to figure out what thing I accidentally typed incorrectly it gives you decent errors this is a while ago but if you do make a mistake and you're codable object it will give you a pretty helpful error in terms of what you did wrong for example if you forget a particular key or if you have a typo it'll tell you that it was expecting a particular key in your struct or your class and it didn't find it and string okay and then this one looks like it's an integer hopefully there's no there's no floating points so it's not a double or a float or anything so I think we'll be good to go if we just make it an int and we also need to understand that we're not putting optional in front of any of these you could if you have a case where one of these values might come back as nil by making them non optional you're telling the JSON decoder we're gonna use in a minute that every single property must exist in the returned response otherwise it's not a valid response so how do we actually convert 482 bytes to this thing right how does that magic happen so it's super simple so we're gonna first create a result so it'll be the type that we want optional and we're gonna put a do catch block here the reason we need this is because the decoder function can actually throw an error so we're going to save JSON decoder and we want this function to code and notice the the two parameters it takes is the first thing is the thing that you want to decode to so that's gonna be our type dot self and the next thing is gonna be the data you want to decode from and we're gonna make that data and we need to put a try here like I mentioned because we need to try to do it it can throw and if an error occurs we're gonna print out an error we're gonna say failed to decode with ever like so and now we should probably unwrap this because it's optional spell that correctly I'll say final equals results else we can return and now let's print out some of our data so let's actually we'll type it again well say prints final results and see what stuff is in here so results points to this thing there's sunrise sunset day length let's print up those three say sunrise sunset day lang so uh so yeah that's that should be everything we need to do so let's go ahead and hit command K in here to clear that out it pause now let's say it run one more time and if you look about it instead of seeing our bites we actually see the data here so let's go validate that this looks correct so twenty twenty eight zero one 1732 oh six oh six zero zero feel like I spelled these incorrectly these are both sunset we want one of these to be sunrise and that's the order right nope sunrise comes first that should kind of be obvious my mistake let's try that one more time let me go ahead and clear this stuff out and run it once more and okay perfect now we have differing values let's go double check these so the sunrise we should get back is twenty twenty eight one one forty one twenty twenty eight one one forty-one so we're definitely getting the correct data back and we're decoding it's not being mocked or anything for this video but that's basically codable in a nutshell like I mentioned it's pretty simple it's really the concept of providing the keys and types types that uh the decoder object can try to translate bytes to right so it takes the data and you're giving it this object and you're saying basically try to convert from this to this and that's what you need to try because it may or may not succeed and fun fact if you come and click into codable codable is actually just a wrapper of code encode opal and decodable so if you're curious about what both of these protocols are as their protocols themselves under the hood you can definitely google to apple's documentation and take a look at some of the nitty-gritty about it it basically allows you to decode from bytes to the object or the inverse which is create bytes from the object so in our example here we basically took data which is bikes and we converted it into the struct but we can also take the struct and convert it into data let's say we want to upload something for example so codable is just a fancy wrapper on top of uncodable and decodable and it just aggregates the functionality of both together so that's really it that that's really all there is to it dealing with JSON and Swift is amazingly easy it's a huge deal when it first came out it was a huge deal and code Apple God added I love it you'll love it too it's an essential part of every project and that's kind of all I had for you so if you haven't hit that like button already make sure to do so for the YouTube algorithm comment down below if you have any questions suggestions concerns issues etc I try to reply pretty soon to each comments if you haven't seen my memberships video I have YouTube memberships rolled out now so take a look at that if you're interested thanks for watching and I will catch you in the next one
Info
Channel: iOS Academy
Views: 6,855
Rating: undefined out of 5
Keywords: swift 5 tutorial, swift codable 2020, swift json, swift make api call, swift handle json, swift for beginners, swift 5 2020, swift tutorial, swift, swift codable protocol, swift what is codable, how to use codable in swift, swiftui codable, swiftui tutorial, swift protocol, swift basics, swift programming, how to make app in swift, swift make first app, swift how to make app, swift developer, swift ios developer, how to make iphone app, swift tableview, tableview custom
Id: w7xJrAYQoHE
Channel Id: undefined
Length: 14min 17sec (857 seconds)
Published: Thu Jul 16 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.