How to use Do, Try, Catch, and Throws in Swift | Swift Concurrency #1

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] all right welcome back everyone we're gonna start off this playlist with probably the easiest video in the playlist we're gonna cover do try catch and throws these are four keywords that are not new to swift or swift concurrency but they are probably new to this channel i have not really used them or covered them in detail on this channel so i want to address these first before we start using them in every video going forward uh these keywords i have not come up much so far on my channel but they are very important and used almost every single time we write asynchronous code using swift concurrency so many of you probably already know what these keywords do but one thing that we're gonna look at in this video which is pretty interesting is sort of like the evolution of swift uh instead of just showing you guys how to use the keywords we're gonna talk a little bit about why we're using these keywords because the why is almost more important here the why helps us understand why we want to use these in swift concurrency and going forward all right welcome back everyone it has been a while since i've made a video so excuse me if i'm a bit rusty but let's jump back in here let's open up xcode let's start a new project i'm going to create a new xcode project and just like all the other bootcamp playlists we're just going to create a regular app here i'm going to call this one swift concurrency bootcamp and i'm not so concerned with the team or organization identifier or the bundle id because we're not putting this into the app store but it is important to make sure that our interface is in swift ui and our language of course is swift what else would we be coding in right guys we are not going to use core data we are not going to write tests uh maybe we'll write tests later but i'm not going to do that for a while so we'll leave those unchecked let's click next let's find a place to save this on your computer go ahead and click create once we are inside i'm going to make this full screen let's get that simulator working and let's get coding i'm going to switch my simulator up here to iphone 13 just because it looks way better than the ipod touch don't know why that is the xcode default and we're not going to use the content view but we're going to create a new file for this video so let's right click the navigator create a new file it'll be a swift ui view let's call this one do catch try throws boot camp click create and once you're inside there let's uh click resume the canvas one more time and get coding and as i kind of pointed out earlier what we're covering in this video is not actually new to async weight but we are covering keywords that we use in async weight a lot and on my channel at least i haven't covered them uh that often because we haven't really used a lot of these keywords uh at least until async await so we're gonna cover in this video is do catch statements as well as the try keyword and the throws keyword and as you guys are gonna see all these keywords kind of work together so that's why i'm putting them all into one big video here and i'm going to move a little quickly here because a lot of the stuff we're going to do should not be new to you guys so let's start by creating a view model for this view so let's create a class let's call it a do try catch throws boot camp view model that's conformed to observable object and let's initialize one in our view with an at state object private var vm and we'll set it equal to do try catch do catch try throws boot camp view model i'm gonna actually start calling my view models view models in this playlist rather than vm i think it's just a little bit more clear for anyone who's just joining and we're gonna start super simple so in the view model let's create an app published var let's call it text of type string and i'll set it equal to starting text i'm going to put that on the screen so in here we'll call view model dot text and there shouldn't be an s here let's give this a quick frame with maybe a width of 300 a height of 300 and i'm going to give it a background color of color.blue i'm just doing this because i just want to be able to see it on the simulator here i don't really care what the view looks like in this video and we're going to do a very simple dot ontap gesture and then we're going to perform a function so in our view model here let's create a func called fetch title open close parenthesis open the brackets let's call this from our tap gesture so in here we'll call viewmodel.fetch title when we fetch a title we want to update this text but generally in your actual app you're not going to really do your entire fetch request inside your view model you probably have another class a manager class or a data storage class or some sort of you know data loader and that's where you're going to get your data from so let's simulate that let's create another class let's call this one maybe do try catch throws boot camp let's call it data manager and we'll open the brackets and in here we're going to have another function that says maybe get title and this function will then return a string so in here let's just return new text why not let's get a reference to this manager inside our view model so we'll say let manager equals do try cash throws boot camp data manager what a mouthful uh generally of course we're not going to initialize this in our view model we're going to inject this i do have a video on dependency injection on the channel if you want to check that one out but now that we have this reference inside here we're going to call manager.gettitle it's returning us a string so we're going to say let new title equals that and then we'll set self.text equal to the new title cool i'm going to click resume on the canvas here i'm going to press play and then tap on our box and we got our new text you guys probably already noticed that we have not used any of these keywords yet and that's because we're going to build up to using these keywords because i want to really explain to you guys why we use these keywords not just how to use them once you understand why it actually makes a lot more sense on why we then want to use these in swift concurrency so as a developer this is great this is all working perfectly but the question is what if we go to fetch our title and maybe sometimes we don't actually get a string back maybe there was an error or a problem fetching that title well how could we improve our code here so let's simulate that error we'll say maybe uh let is active of type bool we'll set it equal to false and just to simulate so maybe when we call get title we check if is active and if active is true we return the new text if not we'll do something else so in here we'll add if is active and then we'll return our new text and we'll say else and if we and if it is not active let's then return nothing so we're going to return nil so we can improve this by then returning making it optional and then in our code down here we could just very simply check if let new title equals new title and then we can put our code in here so again i'm going to click play here i'm going to click on this and as you probably can see already if i click and press on this nothing is changing and that's because is active is false so we're returning nil and then nothing's happening in our app so already off the bat we can see that there are limitations to just returning an optional right as a developer we know that is returning optional because it failed to get the text but if you're sharing this code if other people are using this code that's not very clear and it might look like a bug in your application if maybe things are just not updating right so so often times instead of just returning nil from a function we want to take it a step further and maybe return an error instead so an easy way to do that would be maybe from this function instead of just returning a string let's return uh maybe two pieces of data we'll return a title as well as an error and we'll make this optional right so now we can get a title and we can get an error so if is active is true let's return new text and of course our error will be nil and if and and in our else we're going to say nil for the title and then we'll throw back an error and in your actual app you're going to want to use a real probably a custom error but we're just going to use a url error here and we're going to call bad url it doesn't really matter what we're throwing back here i just want to get this going and the value we're getting back here is actually a tuple and we can see that it has a title and also an error so we could just name this maybe returned value and we can check if let new title equals returned value dot title and then we can say else if let error equals return to value dot error so if we're getting that error back we'll call self.text and put on the error.localized description just for a second so i'm gonna run this one more time and i'm gonna click on it and you probably guessed we're getting back that error uh this is good this is a bit better in our code right because now we we have the ability to check for real values and also check for errors but this is kind of a hassle for us as developers because really we want to return a result here either this function should be successful or it should fail it shouldn't really return us a title end an error right we should really probably only be getting one or the other there's never really a use case where we're gonna get both of these so how can we improve on this even further so i'm gonna create another function here so i'm gonna create another function i'm gonna call it get title 2 and this will return us a result and i'll open the brackets and as you're going to see here a result is actually a generic type so we need to provide the success type as well as the error type on failure so we'll click fix and the success type that we want to return back is a string and the error type is just going to be a regular error now i'm going to do more or less the same code as we did here so we'll say if is active and if it's active we're going to return success and that's going to be a string so we'll say return dot success and we'll put in that new text then we'll say else and we will return dot failure and we'll put in our error so i'm going to put my error back up here put it into here so now let's call get title 2 from our code so in i'm going to actually comment this one out so i'm going to forward slash asterix and down here i'm going to asterix forward slash do a multi-line comment and then while i'm clicked right in front of this i'm going to fold this up with the option command left arrow that you could also go to the editor go to code folding and fold that up i love folding code it just looks so much cleaner uh now we're gonna call we're gonna say let result equals uh manager.gettitle.com and we can see here that we're getting this result if you've ever used combine and i've done that a lot on this channel when we use combine a lot of times we call sync and then we have a completion and we switch on that completion usually it's either successful or it's failure that is a result that's the same thing that we're getting back here it's either got a success case or a failure case so we'll call get title 2 and then we want to switch on that result so i'll say switch so i'll say switch and i'm going to switch on the results and the case is dot success let's say let new title and this will be the title we get back we'll say self dot text equals new title and our other case of course is failure we'll say let error and finally self.text is going to equal the error dot localized description all right i'm going to give this just a different error just so we get a different error message on the screen here let's click resume i'm going to run this one more time and we should get a error back on the screen again and there it is so already your code's a little bit better now because this is if you're sharing this with other developers or even if you're just coming back to this at a later date it's much more obvious here if we call this function it's going to give us either a successful state or a failure state right it's no longer giving us back both and then we have to kind of manage which one is which and and look at both cases and look at all the data instead now we just get back a result and then we can either take can identify very easily if it's a success or a failure and you're probably thinking at this point what on earth is this guy talking about because he told us we were going to learn do catch try throws and we haven't used any of that in this video i know i know we haven't i was a bit hesitant to even go down this route but this video is not over and we're gonna jump into it right now so we can actually basically improve on this even further right so right now uh every time we call this function we then have to switch on that result but really we know when we're calling this we either are going to get back a success or a failure so wouldn't it be nice if this function could just give us back one or the other and rather than giving us back a result that we have to then check and that's kind of where uh try and throws come in so we're going to create we're going to create another funk here and it's called get title 3 you probably guessed it and let's open the brackets now this function we're going to go back to basics as we did in the first get title we're just going to return a string we're going to say if is active and we'll return our new text and then we'll say else and the question is if we can't actually get our data here how can we then exit out of this function right because we can't just return a string we don't want to return a nil value we don't want to return a blank string instead we want to throw an error back out of this function so the same way we we passed an error back here we called our a failure state here and passed in an error we just now want to just throw that error back out and the way we do that is by marking a function as throws meaning it can throw an error and then in here we can very simply throw an error so i'll call url error and we will then use whatever error we are going with here so the way to read this function is that is a function called get title 3 that tries to return us a string but if it fails it will throw us an error so that's the beauty of throws right so instead of returning a result and then switching on the success and the failure we can just return a string or throw an error so let's use this in our code now i'm going to come down here i'm going to make another multi-line comment and fold this one up as well and let's let's do this one more time we're going to say let and we're going to say let new title equals manager dot get title three and you can see here when we call this that we can see that it throws very explicit here and it returns us a string so the value that we're going to set here is actually going to be the string if it is successful so i'll call get title 3 here and now when we do this we're going to get our first compiler error it's kind of annoying the first time you hit these but it's actually so handy because this is literally the compiler telling us how to write our code we don't have to worry about it as developers if we're doing something wrong so what this is saying is that this call can throw but it is not marked with try and the error is not handled and that's actually exactly what is going on here this function is a function that throws us errors right and we're gonna try to get a string and if we can't get it we're going to get back that error so the way to convey that in our code is to literally try to get the result of this function so the question then becomes if we are trying to get it but we actually run into an error if this actually throws us back an error what where are we going to catch that error and you can see here that we're still getting another error here that our errors thrown are not handled and that's because we are going to try to run this but if not we need a place to catch those errors so what we do is actually create a do catch statement and you can see when you create a due cache the first thing is in inside the do is all of your tries and then there is a catch where you're going to catch all of your errors so i'm going to take this code put it inside the do here and then we can catch our error so so in our catch block we can then name the error if we want to give it a local name so we'll say let error and then in here we can do what we've done before we'll say self dot text equals the error error.localized description inside of this do if we do get this new title let's then just set that to the text so we'll say self.text equals new title let's click resume let's do this one more time and we should get that error back here awesome and so now let's take a closer look at this do catch statement so the do has a do block and in your do block you're going to have all of your try calls these are all of your functions that can throw errors now if there was multiple calls that we needed to try to make here we can put a bunch of calls in this block it's not limited to just one try right we can keep trying but if any of these tries were to fail we're immediately going to exit out of this do block and jump into the catch block and i'll get and i'll get further into that in a couple minutes but for right now we're going to try to get this title if we are successful in getting this title we're going to execute this line of code but if we fail to get this title this line of code will never execute and instead if we fail this we're going to immediately jump into our catch block and that comes down here a really handy thing about these catch blocks is that if we want to just call it error we actually don't need to even give it a local name here so we can just it can just imply that and we can keep our function working as it is all right so we covered do we covered cash we covered try we covered throws and now i want to run you guys through a couple quick examples of using this try keyword because it is a little bit tricky so let's create another function up here let's just call it get title four and get title four we're going to return let's say maybe a final text just so it's a little bit different so we know if this one is actually returning here and let's come back down to our code and what we're going to do is say let final title equals try manager dot get title 4. they're going to say self.text equals final title so now we have two different try statements inside a single block and before we run this let's actually go back come back up here and make is active true so both of these should return values so this one will be successful as well as this one so let's run this one more time now i'm gonna click play on the canvas here and we can see that final text is coming through so we are running title three it's setting the new value then we're running title four and then it's setting the new value as final text and you can see that this is working perfectly what i want to show you guys is that if one of these tries fails the rest of the do block will not even execute so in this get title three let's actually just throw this error every time so i'm just going to comment this out quickly and we're just going to throw an error every single time we call get title 3. so we know right now when we call get title 3 it's going to throw an error we know when we call get title 4 it's going to be successful but if i run this and i click on it you're going to see that we get that error back even though get title 4 would have been successful and that's because as i was saying once you fail one of these try statements you immediately go into the catch block so if we fail this we're never going to execute the rest of this that's really important that leads us into the next use of try you can actually make try optional and when you make try optional you're telling the compiler that you actually don't care about the error that's coming back and instead of getting an error back if you fail you'll just set that value as nil so if i take out this try and i hold the option button and click on new title we can see that it's a type string because we are this is a hard try we're going to get back that string but if i make this try optional hold the option button and click on your title we can see that it is an optional string so again we're saying here we don't really care about what error is coming back if there is an error we're just going to return nil so the beauty of using the optional try is that you don't actually need to use it in a do catch because you're not actually going to throw any errors into the catch so for some for a lot of simple cases you could actually just take these i'm going to copy this and let's actually remove the question mark here i'm going to put it up here so we can say let new title equals try this and we'll say maybe if let new title equals new title self dot text equals new title so if i comment this out here and i go to run this let's see get title 3 is throwing us an error so even though it's throwing us an error we're not actually doing anything with the error so this will just be optional when i click this nothing happens if i uncomment this code put this back in here we can see that it's now working again so the biggest benefit of the optional try is that firstly you don't need to do catch block and then it saves you a bit of time as the developer if you don't really care about that error anyway sometimes if you're using like third-party apis and they're throwing you back errors but you don't want action but you're not going to actually display that to the user maybe you don't really care about the errors that are being thrown back but before we move on i want to actually show you guys using the optional try in the do catch block so i'm going to comment this out up here we're going to make this one optional we're going to say if let new title equals new title and we'll put this inside this flat statement i'm going to make get title 3 fail every single time just like we had before so let's comment this back out let's throw that error every time so now we know this will throw an error but this one will not and if i run this again and i click on it you're going to see that final text is coming through so even though get title 3 is throwing an error now we are not coming into this catch block so before we threw an error we did not run any of this code and we just jumped into the catch block but here because we marked this try as optional we're not actually going to throw the error we're not going to actually catch that error so even though it's throwing it so even though it's technically throwing an error from the function up here we marked it as optional so we're not actually going to throw it out of the do block i hope that is clear on this same note you can also explicitly unwrap a try so i could do something like this and then the new title will be a string 100 of the time we don't need to unwrap it at all now again explicit unwraps are super dangerous i do not use them in code i do not recommend using them but i wanted to show you guys that they are there i'm going to comment that back out and i think i'm going to wrap up this video there so you know decently long video here we didn't cover anything related to async or weight but most of our asynchronous code in our asynchronous and our asynchronous functions are going to actually be functions that throw errors so this syntax is going to be really really common in async await and when you're using throws you're almost always using do catch statements so this code is going to be super common in all the videos going forward and that's why i wanted to cover this first i hope that does clear it up for some of you because i haven't covered this on my channel before honestly we don't really use these keywords very much outside of async weight at least i haven't very often on this channel so there it is there you have it we covered it do catch try throws some really powerful stuff here and in the next video i think it might be time to actually jump into async oh wait thank you guys for watching as always i'm nick this is swiffle thinking and i'll see you in the next video [Music]
Info
Channel: Swiftful Thinking
Views: 24,608
Rating: undefined out of 5
Keywords: Swift, swift concurrency, swift do try, swift do-catch, swift try, swift throws, swift throw, do-catch, do catch swift, try in swift, throws swift, async await swift
Id: ss50RX7F7nE
Channel Id: undefined
Length: 26min 34sec (1594 seconds)
Published: Mon Apr 25 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.