How to safely unwrap optionals in Swift with if-let and guard statements | Bootcamp #47

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] welcome back everyone i'm nick and in this exciting video we're gonna practice safe coding because safe coding is great coding and what that means is that if we have optionals in our code we're going to safely unwrap them so we can always be sure and check whether or not we have values or whether or not that optional variable is actually nil so the two main ways we're going to do this in this video are using if led statements and guard let statements i'm going to show you a whole bunch of examples on how these could be used how they are important and as you start becoming a better swift developer you're going to find that every time you have an optional and you need to use it it is smart and important to unwrap these optionals the correct way because if you're following other tutorials out there where you are explicitly unwrapping so you're using the exclamation point you're probably going to end up running into a lot of crashes and a lot of errors in your code so instead of using that exclamation point which i recommend never using you can unwrap them safely by using iflat and garlet statements and i think this is one of the most important videos in the entire course and that's because in every single app you're going to run into situations where you have optional values and is always smart to unwrap those variables in a safe way and this applies not only to swift ui apps but also to ui kit apps and pretty much any time ever that you're writing swift code so very important let's take a look so i'm back again in xcode of course and let's create a new file for this video right click the navigator new file swift ui view and let's call this if let guard boot camp you can call it whatever you want we're talking about if let and guard statements so i'm just calling it if let guard boot camp go ahead and click resume on the canvas and let's get coding let's start out by creating our template view here so let's add a navigation view open the brackets in the navigation view let's add a v-stack open the brackets again the bottom of the v-stack we'll add a spacer and on the top we will add some text and for the text let's say here we are practicing safe coding let's add a title to this so underneath the v stack navigation title let's call this safe coding and underneath this text i'm going to add one more text we'll do text and this one let's make it dynamic so i'll add a variable at the top here we'll do at state var uh display text of type string equals and we'll set it equal to a blank string for now we'll take this display text and we'll put it into this text component let's give it a font of title just so we can see it a little bigger click resume on the canvas and when this v stack appears i want to change this text what we did in the last video so we're going to call dot on appear and then i'm going to open the brackets and we're going to put some extra logic into this function so i'm going to create a separate function that we're going to call so underneath the body down here i will add funk we'll call it load data open and close parentheses open the brackets and we're going to call load data on up here so load data we'll put in here and we're going to start off very simply by changing the display text when we call load data so we'll add a delay first we'll call dispatch q dot main dot async after dispatch time is dot now plus let's do three seconds and then execute what code do we want to run after three seconds we're going to say display text equals this is the new data so obviously if this was a real app you would have a call here instead of this line you would have a call to your database to go download some information and then you wouldn't just be displaying a text you display that actual data that actual information that you downloaded but for this tutorial's sake we're just going to change the text to say this is the new data so very simple nothing new so far let's click resume on the canvas and let's just see this in action real quick so i'm going to click play and we don't have any text here and then after three seconds the data should load and says this is the new data so the first thing we're going to look at here is this text component because what if we didn't want to actually draw this whole text field onto the screen until we had the data so right now when it's a blank string and if i click if i stop running the preview right now before this new data loads this text component is actually being drawn onto the screen it's just that it has a blank string so we can't actually see any text but what if this string was something that we didn't want to start blank we wanted to start it as nil so what if this was actually optional so i'll delete that and i'll put a question mark and what if it was set equal to nil at the start so there was no text here well now we get an error because we can't just use this display text because it's basically saying that this is optional there's a chance there is no text here so if there is nothing here and this is nil we can't just put this on the screen so what can we do well we can use an if let statement so we'll say if let text equals display text open the brackets and then we're going to put this text and font inside this brackets and instead of referencing display text we're going to reference this text so put that in here so what this is saying is if display text is not equal nil if there is a real value in display text create a new variable called text with that actual value so every time we reference this actual text we know it's got value so this line creates this new variable text and if it is true if there is an actual value it will run this code but if there is no value in display text we cannot create this object this will never execute and it will skip over this so now we can run the exact same thing except we're starting our display text as an optional string so i'll click resume on the canvas and again after three seconds this text will go from nil to an actual value so then this will be true and this will execute so now we can see this is the new data so now i want to take this a couple steps further to give you a little bit more real world example of how powerful some of this stuff is so let's start by adding a loading indicator to the screen so at the top we'll do at state var is loading of type bool and we'll set it equal to false to start and when we call load data let's put is loading as true so at the top here we'll do is loading equals true and when we actually load that data after we finish loading it let's change is loading back to false so we call load we call load data it starts loading and after we load it we change it back to false and below this if let's statement let's just add if is loading so if this is true open the print open the brackets and we'll add a progress view open close parenthesis on that let's check this one more time so as soon as this screen comes is loading is true so it's loading and then as soon as it loads that progress indicator goes away this is looking better and now let's simulate like we're actually loading some data for a user in our app so we'll create one more variable up here we'll do at state var let's call it current user id of type optional string and we'll set this equal to nil again so now sometimes in your app you have situations when people are using your app and they're signed in and they'll have a user id but you also have situations where people are using your app and they are not signed in they never made an account and they don't have a user id so in this example we're going to pretend like we only want to load data if they actually have a user id so when we call this load data function we don't want to immediately just start downloading our data we first want to check is there a current user id so let's use an if let's statement for this so we're going to do if let user id equals current user id open the brackets so if there is a current user id let's create a new variable called user id and then we will run this code and we'll run this code here which i'll cut and paste it so now we are only going to run this if there is an actual user id and we're getting this little warning here because we're not actually using this user id so let's just use it let's put it into this text string here for now so we'll do so let's just add user id is colon forward slash open and close parentheses and we'll put in the user id so right now if i click resume on the canvas i'll zoom out a little bit here i don't want to zoom out too far in case this is hard to read but right now we can press play on the live preview and we know that current user id is equal to nil so we're going to call load data and it's going to say if let user id equals current user id so if there is a current user id create this variable and then execute this but we know current user id is equal to nil so this is false and this is never going to execute and that's why we never see the loading indicator and we never download the data and never gets updated on our view so what i'm going to do here just for this just for this sake at the end of this if let i will do else open the brackets so if this is not true and there is no user id let's just change the display text equal to error there is no user id so if we run it one more time you'll see that immediately this is false so go straight to this is the error there is no user id and if we go to the top and we change it so there is an actual user id so let's do test user one two three and if we resume this again now we can see the same function is getting called but it's checking that there is a user id and then it is loading our new data and we can see the user id is test user one two three so this is the power of the if let statement because we can always just check that we do have a value before running a certain piece of code so up here we're checking if we have a value before putting some text on the screen and down here we're checking if we have a value before we're actually calling some code to download from our database now before we go i also want to introduce you guys to guard statements which are very similar to if let statements and we're going to actually create basically the same function again but we're going to do it but this time we're going to do it using a guard statement so underneath this load data let's create another func let's do func load data 2 open and close parentheses open the brackets so we're going to do basically the same thing and the first thing we want to do is check if there is a user id so this time we'll put guard let user id equals current user id else open the brackets and in this else we can put the code for if there is no user id so up here we had this bracket and then the else was down here but now the else is at the top and we're just going to put this line of code into the else so so we have the else and then we're getting a quick error because they guard the body must not fall through there must be a return so all we need to do is after this display text we will call return so what's happening here we are saying guard let user id create a new variable called user id and it will be the value that is in current user id so if current user id is equal to nil we won't be able to create this new variable and then this will run but if there is a value here then we're going to create this new user id so if it's successful the rest of the function down here will run but if this is not successful this will run and then we're going to return which basically means get out of this function so once you hit this return nothing below this will execute so first we check if we have this user id and then if we do have this user id we want to actually load the data so i'm going to copy these lines of code here from the is loading through the dispatch queue i'm going to copy it and i'm going to paste it down here below the guard statement so again first we're checking if we have this user id if it if it's false if the user id is nil it's just going to run this but if it's true it's going to run the rest of the function and this function is the same thing that we have up here these two functions are exactly the same except this one uses if let this one uses guard let and as a developer you can start to figure out which one you want to use in which case they both do the same thing i personally try to use guard statements more just because this looks a little cleaner to read but let's test this out quick so on up here i'm going to call load data 2 instead and let's start by setting the current user id equal to nil click resume on the canvas and when the current user id is nil this guard statement is failing so we can't create this new user id and of course the display text says error there is no user id and that's why we see it if we change the current user id back to testuser123 and we run it again we click resume this guardlet will succeed we'll create a new variable called user id that we can use in our function and the rest of this function will run and then we can see this is the new data with our new user id and the the last thing i want to mention here is let's instead of using this if let's statement let's just add this text with the display text directly so we'll do text open parentheses and we'll add the display text let's copy the font modifier onto this and we're going to get that error again because this display text is optional now if you've taken other online coding courses you've probably seen people force unwrap optionals and that means adding that exclamation point so if you ever see someone using this exclamation point most likely it's bad coding and there's a better way to do it because by using if let's statements you can always check if there's a value rather than force unwrapping because yes the error goes away when we force unwrap with the exclamation point but if there is no value in this display text we're going to get a crash because right now if this is nil and i try to resume it's not even going to let me resume because this won't compile because this is causing a crash because we don't actually have a value in here so i'm getting a crash here the bottom line here is i'll put a comment do not use exclamation point ever another way of saying that is do not force unwrap values in a production in production code that you're actually going to put in the app store i would pretty much never have this exclamation point and if you're seeing these exclamation points then there's probably a smarter safer way to manage your data and and chances are the solution is going to be using if let or guard let statements but do not force unwrap values so i'm just going to comment this out do not force unwrap unless you absolutely have to but you pretty much never have to so if let or guard statements is safe coding and safe coding is great coding so i hope you guys enjoyed this video if you have any questions or you're confused about anything definitely leave it in the comments below and i will try to clear up whatever i didn't clear up in this video bottom line if you take anything away from this video is do not force unwrap values and safely unwrap by using if let and guard statements thank you guys for watching as always i'm nick this is swiffle thinking and i'll see you in the next video
Info
Channel: Swiftful Thinking
Views: 2,060
Rating: undefined out of 5
Keywords: SwiftUI Bootcamp, Learn SwiftUI, SwiftUI guard, Swiftui if let, Swift guard statement, swift what is guard, Swift what is if let, Swift how to unwrap optionals, Swift unwrap optionals, SwiftUI optionals, Swift explicitly unwrap optionals, Swift optional, How to unwrap optional Swift, Swift guard, Swift what is guard, Swiftui guard statement, Swift safely unwrap, SwiftUI safely unwrap optional, Swift optional is nil, How to unwrap optionals in Swift, Optionals in SwiftUI
Id: wmQIl0O9HBY
Channel Id: undefined
Length: 18min 13sec (1093 seconds)
Published: Sun Mar 07 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.