Learn Swift Fast (2020) - Full Course For Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to my Swift tutorial for beginners if you want to learn Swift programming even if you've never coded before then you're in the right place I'll take it step by step and by the end of this video series you're going to have a solid foundation in Swift programming all right stay tuned my name is Chris and I'll be your guide and teacher on your swift journey now before we dive in I need to tell you about two things that are going to be critical for your success number one you have to keep in mind that this is a journey and I'll elaborate on this in a second number two is that you're going to have to get your hands dirty now these two lessons I've had to learn the hard way through my own failures when I first started learning Swift programming I failed and that was because I just kept learning and learning and as I was learning everything made sense in my head but when I finally got to coding I realized that I didn't retain a lot of what I've learned and I don't want that to happen to you so it's really critical that you practice and I'll help you along with that and the second thing is that as with any journey worth completing there will be ups and downs you probably will be pretty confused in the beginning but I guarantee you stick with it and you'll come out the other side a swift developer all right now I know you're itching to get started but just one last thing for your success if you ever get confused or get stuck you could simply leave a comment below and we're going to jump in and help you out or you can join our free code with Chris Facebook community where the team and I hang out as well as other iOS learners all right now that you have the right frame of mind let's take a look at what your swift journey is going to look like in this lesson we're going to get you set up and oriented with the tools and we're going to dive into our first Swift topic which are variables in the next five or six lessons after that you'll learn more Swift you'll do more hands-on coding and with each lesson you progress through you'll be layering and building up your skills becoming a stronger and Swift e're programmer then from lesson seven to eleven you'll be learning more about how swift code is structured and organized and how it's actually used now even if you just get up to this point you'll have a pretty solid foundation understanding of how the Swift programming language works and how to use it but we're going to take it even further from that point on you're going to continue learning new Swift concepts and goodies that will enable you to do more and more with this wonderful programming language oh and I forgot to mention in between these lessons I'll sprinkle some challenges and exercises that I highly recommend you do because it's gonna help you discover your hidden knowledge gaps okay so with that said let's jump right in alright so first things first where do you write your Swift code well ideally you want to be using a swift code editor because that way you can compile your Swift code execute it and take a look at the results well Apple has released a tool called Xcode just for this purpose now using this tool you can write your Swift code build your user interfaces and build apps across all of those different platforms and what's more this app is completely free the only drawback is that it's made from Mac computers and there is no PC or Windows alternative but if you're on a PC it's not the end of the road for you because there are other alternatives such as browser-based solutions you can type your Swift code directly into the browser and execute it and then take a look at the results you're not going to be able to build out this way but you're still going to be able to use it as a learning tool to learn Swift programming language I wrote an article explaining all of the different options that code with Chris calm slash Xcode for Windows now if you are on a Mac all you have to do in order to get xcode is go to the mac app store and then search for xcode here you're gonna see this listing here now don't be fooled by the low ratings this is the tool that all of the professionals use to build apps on all of the Apple platforms it can be a little bit confusing at first when you launch it and from time to time it is buggy however it is the official Apple tool so it works and placed nicely with the rest of the Apple ecosystem including submitting apps into the App Store's so what you're going to want to do is download and install Xcode and you have to also make sure that you're running the latest version of Mac OS because if you scroll all the way down here take a look at this compatibility section if this doesn't say it works on this Mac you can you can actually click it and they'll tell you which version of Mac OS it requires you want to go up here and check your version of Mac OS on your machine and if you have a lower version you can just search for Mac OS in the App Store right here and it's gonna be a free upgrade for you the only question is does your machine support this latest version of Mac OS even if it doesn't and you can't get the latest version of Xcode I wouldn't let that stop you use one of the browser-based solutions because you're still going to be able to learn Swift and practice with even without Xcode alright so after you've installed Xcode go ahead and click on open and that's going to launch Xcode for you now you're going to get this sort of welcome dialog and we're not going to create a brand new Xcode project instead we are going to get started with a playground and that's just a lightweight little window where we can type in our Swift code and execute it to take a look at the results it's perfect for learning Swift if you don't get this welcome dialog you can always go up to the file menu go under new and then choose playground so if you have this welcome dialog just click on get started with the playground we're always gonna end up in this place where we're gonna choose what type of playground we want to create so under iOS choose blank playground and you can save it anywhere you want make sure you remember where you save it so you can access it I'm just going to save it on the desktop right here now before we dive in here let's do a quick tour and let me show you all of the different elements of the playground so obviously this big main section here is the code editor this is where you would be typing in your Swift code and there is some sample Swift code here we're not gonna worry about that just yet I also have some line numbers which makes it very easy for me to refer to the different lines of code if you don't have line numbers and you want to enable them just go to Xcode preferences under text editing and you can turn those line numbers on or off now you'll also notice that you when you hover your mouse under the different lines the sort of blue play icon follows you and when you drag it down and highlights all of those line numbers in blue well when you click this run icon it basically just runs the code up to that point so if I drag it to line number two and I click this blue button it's just going to run that first line but if I drag it all the way to the bottom here at line four and I run this it's going to run all the code of that point out to line four and you can see here at the top there's a status bar which tells you the current status of the playground it should say ready for you and that means it's going to be ready to accept your code and run it there are some options up here for some different views the one I want you to click right now is this debug area hide or show the debug area and this is also referred to as the console area when we're going to be testing our Swift code we're going to be outputting information into this debug or console area so I want you to make sure that you have this tray enabled and that you can see the output that's going to be shown there this right-hand side here is the preview of your lines of code I wouldn't pay too much attention to this because from version to version of Xcode it may look a little bit different where I want you to focus is in this debug area down here because that should be consistent with what you're seeing in the video now there's one more thing I want to draw your attention to and it's this button down here now this will stop executing the playground so if I hit stop you can see that it enables this guy again and you can also click this button it's turned into a play button when you click on this icon it's going to execute your entire playground if you hover your mouse here and you choose you know a certain line of code to run the code up till that just gives you greater control if you want to run like a segment of your playground rather than the entire playground which is what you would click here now another thing is that if you click and hold this play button you can see that there are two options it's set to manually run which means that every time you want to run your playground you're going to have to either click on this play icon or choose a line and hit this blue play icon but if you click and hold it and change it to automatically run every time you edit the code it's just going to automatically execute your playground and update the results now sometimes this can be a little buggy and as you can see here it's running my playground sometimes this takes a long long time for it to be ready again and sometimes you know when it's constantly running your playground like this you're not going to see the updated results it doesn't work as perfectly as we would want so if you're having some trouble with you know you not seeing output on your playground and seeing that this is continually running then what you might want to do is just click stop and click and hold it and change it to manually run and when it says ready you're going to be able to click and run your code all right so now that you're a little more familiar with the playground and all of its controls and different windows now we can actually dive into Swift code so when you're coding you want to have the mindset that you are giving the computer instructions on how to process data now take for instance a stock portfolio app if you are building an app like that you'd have to write code to tell the computer where to grab the stock prices and then tell the computer how to manipulate that it maybe come up with the percentage lost or percentage gained and then you're gonna have to write code to tell the computer instructions on how to display that to the user in a table format another example take for instance a photo app kind of like Instagram you're gonna have to write code to tell the computer where to grab the images right and how to display them to user and if the user is taking a photo and trying to upload it to their account you're gonna have to make sure that you have code containing instructions on how to take that image data from the user's phone and then where to upload it to some sort of file server and make an entry in a database so when you're coding you're always writing instructions for the computer on how to process different types of data and in the next lesson we're going to talk more about different data types but in this lesson we are going to I'm going to demonstrate some simple pieces of data for you so let's take a look at the playground right now and we're going to ignore what's on the screen right right up here these couple lines and I'm just gonna show you some data so here some number data right that's 123 or we could have like a decimal number that's another piece of data at zero point seven or we're gonna have some piece of text and text this surrounded by two quotes like that and that's a piece of text that's another type of data now the data is stored in the computer's memory which is how the computer keeps track of where the data is and what it is in order for us to work with it we're going to need a way to reference that specific piece of data and that brings us to our topic for today's lesson which are variables and variables are a way for us to keep track of a certain piece of data so now let me show you how to write swift code to create a new variable in order to keep track of a piece of data in memory so in order to create a new variable you type in the keyword var or var followed by a space and then you can type in a variable name now you can name your variable anything you want but it should be descriptive for the data that that variable is going to keep track of so for example if I had a piece of data that was someone's first name I might name my variable first name and nearing the end of the lesson I'll tell you some more best practices about naming variables for now let's write first name and that's going to be our variable name so just like that we've declared a new variable called first name now at the same time you can also give a piece of data for this variable to keep track of and we do that using the equals sign so you're going to write a space and then an equal sign and then you're going to write another space followed by the data that you want this variable to keep track of so since we named this variable first name why don't we give it a piece of text containing the word Tom so let's recap what this line of code does so we've got a piece of text data Tom and we need a variable to keep track of it so we're declaring a new variable using the VAR keyword and we're calling this variable first name and then we're using the equal sign to assign that piece of text data to this first name variable now let's jump back into the playground and let's try this out so I'm going to erase this sample pieces of data that we had here and you can see this line of code actually this line of code which came with our playground is exactly what we just showed in our slides except that this time the piece of data is hello playground and the variable name is STR so here we're going to write in the line of code that I just showed you so you want to write var space and our variable name is first name followed by space and then the equal sign and then space followed by our piece of text data which is Tom now what we've accomplished here is that we've declared a new variable called first name and we've assigned the piece of data tom to it now whenever we want to work with that piece of data Tom we can just refer to our variable first name so now let's try working with our variable what we're going to try to do is output Tom down here in the console area and there's a command called print followed by two parentheses like this and in the middle you can give that command something to output into the console area below so why don't we try typing in first name in there and what we're going to do is you can either hit the execute button here or you can hit this blue button right there so let's go ahead and hit execute and you can see here that we've successfully output that piece of data tom so isn't that pretty cool your print command is saying that you want to print the data that is referenced by the variable first name now let's try working with another piece of data let's say var stock price equals 100 hey and now why don't we try printing stock price and let's go ahead and click that line and we output a hundred down there now just as an aside if you're taking a look at the preview here and you might notice this slash end now this backslash n is just a line break or a carriage return that's what puts that output in a separate line down here in the console now what I want to show you is that you can actually reuse your variable so you don't have to declare it again and you can just write stock price you can change the stock price let's say 50 right you don't have to read eclair it because you've already created that variable or declared it so now down here if I print out stock price and I hit the run icon you can see that it's 50 well where that the 100 go well it's basically you've lost track of it because this line of code you're saying that now the variable stock price should keep track of the piece of data 50 so go ahead and give this a try if you're playing around you might notice something like you cannot assign a piece of text data to stock price let's say I'll just use Tom again you can assign Tom to the variable stock price and this is because the variable stock price is expecting number data only in the next lesson when we talk about data types I'm going to explain to you a little bit more about why this is but for now just know that when you declare a new variable as in line 5 or line 8 here using the VAR keyword and you assign a piece of data to it from that point on when you try to reassign data to that variable it can only be of the same type so numbers or text so stock price can only accept number data and first name can only accept text data so let's go ahead and erase this line here so now you know how to declare new variables and how to assign pieces of data to the variable now there's something else you can use to keep track of data and they're kind of like variables these are called constants now the only difference is that when you declare a constant instead of using the VAR keyword you use the let keyword so let's try to clearing a constant here instead of using var I use let followed by space and then I write my constant name so this time let's say it's the last name and then I'm going to use the equal sign and I'm going to assign a piece of data to my constant and I'm just going to write Smith now what's the difference between a constant and a variable well as you saw up here with a variable you declare it once like in line 8 here and then later on you can reassign a different piece of data to that same variable with a constant you can't do that once you've assigned data to a constant you can't assign anything else to it in fact if you try it's going to give you an error so let me demonstrate if I did something like that Xcode would immediately tell you that you can't assign something else to the constant last name because that's how constants work so at this point it might seem that variables are more flexible because you can do more with them and constants seemed a little more restrictive and that's true but there are instances where you would want to use constants instead of variables in fact if you want to keep track of a piece of data and you don't intend to change that piece of data then using a constant would be preferable I wouldn't worry about it too much for now as you get farther into your Swift journey you're going to understand when to use variables versus constants and furthermore when you're coding an app and Xcode has detected that you haven't changed the data in your variable it would suggest for you to change that variable into a constant and then at that point is just a matter of changing the VAR keyword to the let keyword but for now I just want you to know that there are something called constants which work like variables all right and the last thing I want to talk to you about is best practices for naming variables and constants now I mentioned before that you do want to be descriptive with your variable and constant names so that you know what kind of data they hold but there's a balance that because you don't want your variable and constant names to be too long because then it can also be really hard to read and you don't want them to be so short like STR or even maybe just s because then you don't know what kind of data it holds right so I would say one to four words is ideal and furthermore if you had something like three words like very first name or something like that it can still be hard to read so a best practice is to use camel casing and camel casing is just where you have the first word having a lowercase letter and then every subsequent word starting with a capital letter and you can see now that it is a lot more easy to read verses all lower caps okay so before moving on to the next lesson let's do a quick recap you learned that variables are used to keep track of information you learned how to declare a new variable you learned how to assign data to a variable you learned about naming variables and camel casing finally you learned about constants and how they're like variables except that you can't reassign data to them after the first assignment now I know that's a lot to absorb but that's why I have a practice video for you where we're going to go through a couple of exercises for you to get hands-on and dirty with I also have a set of recap notes that you can download now the links to both of these resources are down below in the description below the video all right great job with less than 1 I'll see you in lesson 2 [Music] hello and welcome back to my Swift tutorial for beginners this is lesson 2 if you missed lesson one that I highly recommend that you start there first now back in Lesson one you learned all about variables and constants and how they're used to keep track of the data in your app now the data in your app can be as simple as text or numbers but it can also be complex such as photo data or maybe employee records in a company database in Swift there are different data types to categorize these different kinds of data and that is today's topic so let's dive in so I've got a brand new playground here and I want to show you something that I did a little preview for you in the last lesson so here we have a variable called STR and we've assigned a piece of string data or text data into that variable and I showed you last time that you're not able to do something like this when you reassign data to a variable you can't change the data type now data types were something that we glossed over in the previous lesson but that's what we're going to talk about here today so in Swift there are different types of data so far you've been introduced to strings which is essentially just text data and I know that's a little bit of a weird name for text data but you can think of it as a string of characters at least that's how I thought of it when I first started and then in is for integers these represent whole numbers positive and negative and then you have your decimal numbers and you actually have two data types to represent your decimal numbers where you have float and you have double the only difference is that double is more precise so we can actually store a longer decimal numbers and then lastly for this slide at least we have boolean or just bool and this represents true or false data it's perfect for data where there is only one of two options so those aren't the only data types in Swift however they're probably the most common that you'll work with for a while and also when you get a little more advanced you're going to be able to create your own data types that are more complex than the ones that I just showed you just as a quick example you might create a data type called person which includes a lot of information like your age your hair color your eye color your ethnicity your likes and dislikes and all that sort of stuff that's a lot of data but it's all related to one type which is a person so a quick example quick preview but for now let's just focus on these common simple data types now what I want to do is I want to focus on the practical side of data types so I'm going to show you in terms of declaring variables and constants how you would specify the data type for your variable or constant so in the last lesson you learned that in order to declare a variable you would use the VAR keyword followed by the variable name and for constants you would just use the let keyword and then you would use the assignment operator in other words the equal sign to assign some sort of data into that variable or constant well one thing that I did leave out was an optional part of this variable or constant declaration and that is that after your variable or constant name you can put : followed by the data type that you expect this variable or constant to keep track of so in this example we are assigning some string data to our variable if I were to explicitly declare that my variable can only hold string data I will put colon followed by string which is the data type name so now let's take a look at our playground again Y up here in this variable declaration was there no datatype specified well that's because you don't really have to do it if you don't specify the datatype what's going to happen is it's going to take on the datatype of the first piece of data that you assigned to it so if my first piece of data was actually an integer like 100 then my variable STR would now be an integer data type of variable so now you can see that this line actually doesn't produce an error because I can reassign data to my variable as long as it's the same data type that it took on in the first place now just a quick note why is it that if this variable is an INT type of variable why is it that I can't assign a piece of string to it what's happening under the hood well the thing is different types of data are stored differently in memory and so when you declare a variable STR and you say that it should store integers well to put it in simple terms it's just going to be set up to store integers if you were to say that that variable would store string data it's going to be set up a different way now there is a data type which gives you more flexibility in terms of storing different kinds of data but that's a topic for another day and the second thing is that it actually helps you as a coder because imagine if your variable can store any kind of data you don't know what to expect but the fact that you know this variable STR can only store numerical data or integers to be specific that sets your own expectation as a coder sometimes having too much freedom is not a good thing because it offers more opportunities for errors and when we're programming and when we're coding the greatest enemy is actually us making mistakes either in our logic or in the way that we've coded something so that's a little bit about why there are data types now let's do some quick examples of some of the data types that we've talked about so we've got STR here so let's leave this as a string all right and let's do let's do another one called a I know I'm not following my same rules about having descriptive variables but you know what we could do that let's call it an integer do 100 do a float and this could be like a zero point one or two if you double you know I'm not and you could do a bar fool this is the datatype for that and then this can be true or false and like I mentioned before you don't have to explicitly specify the data types like this it's going to take on the datatype of the first piece of data that you assign to it now this part is a little tricky because float and double both represent decimal numbers it's just that double is more precise so if you remove that datatype or what kind of data type is float and double or sorry these two variables what are they well it turns out that double is the default decimal datatype for swift so this one would actually be a double data type that's what the system is going to treat that as and then boolean is just boolean if we remove that it's going to see true and it's going to make this variable a boolean type okay so before moving on to the next lesson let's do a quick recap in this lesson you learned about the most common data types that you'll be working with you also learn that you can explicitly specify the data type when you declare your variable or constant and if you don't do that the variable or constant is going to take on the datatype of the first piece of data that you assign to it and then the last lesson I did forget to mention that I have a swift cheat sheet available for you to download and reference so you can have quick access in case you forget the syntax or maybe data types or anything else and it's very handy to keep beside you as your learning Swift [Music] hello and welcome to lesson 3 of my Swift tutorial for beginners video series now that you know all about variables constants and data types it's time to start having some fun in this lesson we're going to talk about a staple construct that exists in all programming languages in some form or another and yes I'm talking about the if statement let me show you what they're all about so the reason I'm so excited to show you how to use if statements is because starting from now you're going to be able to write code that can make its own decisions you're gonna be able to write some app logic so why don't we start here with a constant and we're just gonna use a letter A we'll say a equals 10 and I'm going to print a string down here let me just open up the console so you can see something and I want to say let's say a is less than 10 or how about a is less than yeah other a is less than 10 now this is going to print regardless right because well first of all I have to run my playground so there we go a is less than 10 well this actually isn't true right because a is 10 so it's not actually less than 10 and in this case I don't want this to show up well the problem is that that line of code is there right so it's gonna be run and it's gonna show up what we can use here is an if statement so we can add and condition and we can say that we only want to run this print statement based on some sort of condition that we can test so let's see how we can do this with an if statement so it all starts with the if keyword followed by a space and then your condition which are going to test I'll show you how to write that condition in just a second but for now let's continue with the rest of the if statement then you're gonna have a space and then you're going to have a set of braces or some people call it curly brackets inside those braces you're going to have the code that is only going to be if the condition equates to true if that condition turns out to be false then the code inside of your braces will not be running so now let's jump back to the playground and see this in action so I'm going to use the if keyword here followed by a space and the condition that we want to test is is a less than 10 right so we're going to do a and this is the less than operator it's going to check is the left side less than the right side so on the left side we've got 8 on the right side we're gonna put 10 right followed by a space and then we're gonna open up an opening brace and I'm going to go under the print statement and close that brace and press tab here so we've got our line of code inside of an opening and closing brace and this is our condition here so that actually doesn't matter if you want to put your brace down here or up here to make sure there's a space in between your opening brace and your condition now let's try to run our code and press this blue button here this time and you can see that now the console is empty so what happened here was that it checked the condition a is less than 10 and because a is 10 it's clearly not less than 10 the condition equated to false and so it didn't run the code inside here now why don't we make that condition true now all I need to do is say is a less than or equal to 10 in that case this condition would be true right let's press run and then you can see it printed down here all right so that's really cool because now you can write code that can be run based on a condition however oftentimes we've got multiple choices that can be made like for example do you want a Big Mac or do you want chicken McNuggets so we're gonna do this using another feature of the if statement called an else if Clause let me show you how that works so right underneath the closing brace of your if statement you can put the keyword else space if and then you would have another condition then followed by another set of braces now what's going to happen here is that it's going to check your first condition in your if branch if that happens to be false it's going to skip right down and it's going to check the condition in your else if branch if that also happens to be false then it's just going to skip again and it's not going to do anything however if one of those conditions were true then it would run that branch of code and keep in mind it's only ever going to run one branch of code so imagine yourself standing in the middle of crossroads there's two paths one on your left and one on your right there's only one path you can go down right so that's kind of like how the if statement works except that it evaluates the conditions from top to the bottom so the first condition that is true it's going to run that block of code and then it's just going to ignore everything under that if statement so let's jump back into the playground and let me show you how this works so we can say something like let's make a 20 now all right so if we run this code right here that's not going to run because it's false now we're going to use else space if space and let's say is a greater than 15 and then I'm going to print a is greater than 15 all right so if you run this if statement what would you expect to happen it would evaluate this right and since that's false it's going to skip down and it's going to check this which happens to be true and it's going to print that so let's give that a run we've got a is greater than 15 printed down here now let me show you something else what if a was 5 and then we changed this condition like that so this condition test is 8 less than or equal to 10 and this one is is a less than 15 they're both true right I guess I'm gonna have to change this too or else it doesn't make sense so that both of these conditions are true what would you expect to happen when I run my playground right here well it evaluated this condition which happened to be true so it jumped into here this fork of the road right and it executed that branch of code and it ignores everything else it doesn't check the second condition at all so that's really something to keep in mind so another cool feature of the if statement is that you can stack these elsif clauses if you've got more things to check more conditions to check you can just add them to the bottom like that so if a is greater than you know 30 I'm just making stuff up at this point but you can keep going and keep going the only thing is that you don't want to make it too too long there is actually another kind of decision tree sort of structure that you can use it which I'll tell you in the next lesson but in this one just keep in mind that you can check multiple conditions but you don't want to abuse it now I want to tell you about this last feature of the if statement which is the else clause so the else Clause is kind of like a catch-all bucket if none of the conditions at the top evaluate to true it's going to keep checking from the top down right if none of the conditions above the else branch is true then it's just gonna end up executing the code inside of the else branch so the way you include this else branch in your if statement is you use the else keyword and then you just open a set of braces there's no need to specify a condition because remember the point of the else branch is to execute some code just in case nothing above it got executed so let's jump back to the playground and take a look so we've got a is less than 10 a is less than 15 and a is greater than 30 well there's a gap right in between 15 and 30 so if I said something like you know a is equal to 25 and I ran the code right here nothing would execute because none of this is true let's just print something here print a is greater than 30 all right so nothing gets executed right here but if I add an else branch right open up a set of curly brackets or braces here it has something else so why don't we give that a run and you can see that indeed it falls into this catch-all branch of code so now I've shown you all the basics of the if statement however it can get a lot more complex because your conditions inside your if and else if branches can get really complex let's say we introduce another variable here let B equals 10 you can start to chain these conditions together so for example if I wanted to check that a was less than 10 and also that B is greater than 5 and I want both of these conditions to be true in order for that branch to be executed I can use the double ampersand symbol which represents that I want both of those conditions to be true in order for that branch to be executed so let's do B is then I say greater than 5 or less than 5 I think less than 5 and this actually would not be true right because a is 25 and B is 10 so it's gonna skip here so why don't we modify this a little bit why don't we say a is less than 10 and B is greater than 5 so while this part is true let me just run this and I'll show you what the output is right it still falls into here why well although this is true this is not true okay and when you use this double ampersand sign right here you're basically saying that you need both of those conditions to be true in order for the whole condition to be evaluated as true however if you don't care and you only want one of those conditions to be true you know either then you can use the or operator which is actually a set of double pipes I don't know if they're called pipes but this key is on on my keyboard at least is above the return key and you have to hold shift to get them so double pipes will give you the or operator and let me run this code to show you what that looks like so we come into here and execute this now this this Thiemann is a little bit misleading now so I'm just gonna call that branch one branch to branch three and let's say I'm say castle all right so I can run that and show you that this gets printed because we're using the or operator either if either a is less than 10 or B is greater than 5 then we're good we're gonna execute that branch and that's exactly what we get here branch 1 now I'm going to blow your mind further because we can further chain these things so what you can do is you can wrap this condition right in a pair of parentheses like this and then you can say and let's say we've got a third one and let's say we want either B is greater than 5 or a is less than 10 and you know C is equal to 1 right and if we run that it would come into here because this part evaluates to true and this also evaluates to true now we can even go further and we can start wrapping that in a pair of parentheses and you can test as many things as you want and you can build this massive condition but just keep in mind that the more things you put in there the more complicated it's gonna get and the harder it is for anyone to understand I want to draw your attention to one thing though and that is this equality operator here when we're testing equality we don't use the single equals operator here because remember that's for assignment when you do that you're trying to assign one into the constant Z when you want to test for equality you use double equal sign and you when you want to test for inequality you can use exclamation mark equals and that is testing that C is not equal to one so if I run this code right here I would get catch-all reason is because although this evaluates to true this does not evaluate to true and because we're using the end operator there we need both sides of that to be true now if I change this to an or and I ran it we would get French one because even though this isn't true this is true so it's kind of a little bit of logic there which is fun to do and it takes a little bit of practice to wrap your head around now what I wouldn't do highly highly recommend that you do not do this is don't memorize these key words don't go and try to memorize oh I need the if keyword I need a condition here all the operators I can use don't do that because I'm gonna introduce more keywords to you and more syntax to you and it's not going to be fun for you to try to memorize it and it's not practical I've talked all about being practical and what I want you to do instead is spend 30 minutes take a look at the worksheet for this lesson try out the if statement on yourself on a playground and in 30 minutes of learning you're going to learn a lot more and it's gonna sink into your head a lot more you're gonna remember it a lot more than it would if you had trying to memorize this so how to recommend that you do instead of trying to memorize remember I have a swift cheat sheet and worksheets for you to practice what you've learned in too today's lesson I highly recommend you go through that because I don't want you to make the same mistake that I did when I first started now let's do a quick recap you learned that you can use the if statement in order to execute code based on a condition you also learn that you can use the else if Clause to specify alternative branches of code to run based on other conditions and finally you have the else Clause to run some code if all of the conditions above it are not met now one key thing to remember is that the conditions will be checked from top down and the first condition that is true that's the branch of code that is going to be executed and the rest of your if statement is going to be ignored hello and welcome to lesson 4 of my Swift tutorial for beginners now in the previous lesson you learned about how to use the if statement to run code based on some conditions now sometimes when you really get into coding you might find yourself ending up with a giant if statement with so many branches that it's going to give you a headache when you see yourself going down this path I want you to stop and consider using a switch statement and in this lesson I'm gonna show you exactly how to use that so the first thing I want to mention is that there is a Swift programming language guide and I probably should have mentioned this in Lesson one but better late than never I'll add the link to this guy in the description below the video now this contains kind of a walkthrough of the language it's actually it's more in-depth than that it is basically everything you'd want to know about the Swift programming language however it is quite a lengthy read but if reading is your thing then I would highly recommend that you go through it especially if you come from another programming language it's gonna be very useful for you to skim through it see how the structure of the language is the syntax but if you are an absolute beginner to coding if you never code it before this is your first exposure to it then you might get a little bit confused however it's still a great reference in complement to what you're learning here in the video lessons so definitely check it out so I just wanted to point out where we are now I'm not following the exact order that they have listed out here because I feel like the way that they have laid it out is a very slow build-up until you can actually start using the language of having fun with it and building things and so the way that I've laid out this lesson plan for you in this video series you can be vague it's very practical and you can start coding and start tinkering and having fun sooner so I just want to show you where you would find some of the lessons that we've gone through so in the previous lesson we talked about if statements that's under control flow and there's also this little drop down here so if you pull this guy down you can jump to different sections so we are at conditional statements right here so you could see the if statement gives you a couple of examples so it's you know it's really good supplementary material to what we've covered but in today's topic I want to talk to you about the switch statement which is right here so I just want for you to take a look at the syntax here you'll notice that there is the switch keyword here and then there is some value to consider and then a set of braces and inside there's these case and these default keywords you know what I'm gonna show you how it's used inside of a playground and I'm going to use an example so you know it's gonna be a lot easier to understand so let's go ahead and do that so let's pop up an X code here let's get started with the playground and I am just going to switch playground and let's save this on the desktop let's just minimize this guy - what's destruction all right so I can declare a new constant here and let's say that this is a character so why don't we call this a and we are going to assign it a little sign an a let's call it character let's call it CHR now if I wanted to test this constant and see if it was equal to a I could do something like this if CH is remember we use double equal sign or equality testing of quality I mean you know I could print the character is a and then if I wanted to go through all of the letters of the alphabet I could do else if you know you get the picture right it would be a giant if statement not recommended but this is where the switch statement would come in handy so why don't we just quickly take a look at the syntax so just like you saw in the language guide you start with the switch keyword then followed by the thing that you want to check in our example in the playground that was the constant named C HR and then you open up a set of braces and then inside the braces you put all the things that you want to check for and each thing that you want to check for is preceded by the case keyword so it would be case whatever you want to check for first followed by colon and then the code that you want to execute if that case is true followed by the next case and so on and so forth and at the very bottom you have a default case for when none of the cases match it's going to hit the default case and run your code there now let's jump back to the playground and see this in action so let's erase this if statement and instead use a switch statement so we're gonna say switch and actually you can use autocomplete and you just press ENTER like that and it's gonna come up with all of the cases for you or you could type it out for practice so you can see immediately it it's come up with this syntax for me which is really handy because I can actually hit tab on my keyboard and jump through the different things that I have to fill in well I guess it stops right there let's change the value for CHR and the pattern that I want to check for you know the first case would be a right and the code that I want to put here would be this is an a right and then default might be this is all that so let's run this code and see what happens so as expected it hits this case and it prints eight now what if we want it to check for something else let's say be print this is AP and if we just change that to a B and then we run it again you'll see that it skips this case and it comes down here and prints this instead now one additional cool thing I want to show you is that you can actually combine cases so let's say four cases B and C I want to execute the same block of code so I want to say this is this is a B or C so I'm gonna just put a comma here and I can put the other thing that I want to check for it so if CHR is a B or a C then this code is going to be executed and so as expected it jumps down here so this is pretty much it for a switch statement it's pretty easy to use to be honest and it's a lot easier to read than a giant if statement wouldn't you agree now to get more practice using switch statements I highly recommend that you get the worksheet just hop on over to the resources page for this video series to download it all right we're starting to really get into the exciting stuff [Music] hello and welcome to lesson 5 of my Swift tutorial for beginners video series now in the last two lessons you learned how to write code that can be executed based on some conditions now let me introduce you to something called loops loops allow you to repeat a block of code multiple times and while this might sound a little bit boring and repetitive it's actually quite useful let me show you how they work so now I'm gonna demonstrate for you the for in loop and this is going to allow you to loop a block of code for a set number of times let's jump into the playground that I have prepared well I haven't actually prepared anything cuz it's a blank playground but let me present to you this dilemma so if we were to print hello in the console and let's say I wanted to print this five times now I could just write five lines of code like this you know you get the picture but we can use a foreign loop to condense this code into just a couple of lines and let's take a look at the syntax for a foreign loop so true to its name the key words to use are four and in you start with the keyword four followed by some sort of variable name now you don't have to use the VAR keyword here you just give it a name and then you write in and then you specify a range so there's a lower range followed by three dots and then an upper range and I just want to mention that it's an inclusive range so if your range is one to five it's going to loop from one to five and that would be a total of five times and then you follow that by a set of braces inside the braces is where you put your code and that code is going to be looped for whatever range that you've specified so I know that this is yet another set of keywords and another sort of syntactical structure that you have to remember but remember what I said don't try to memorize anything as long as you do the exercises and worksheets after each of these lessons and you just spent fifteen minutes even just trying it out and playing around with it you will remember the keywords to use and the structure of a foreign loop you don't have to memorize anything so that is really the way to go and don't forget I do have a cheat sheet for you to download on the resources page for this video series which you can find the link to in the description below the video so have that cheat sheet besides you and if you ever forget you just refer to it alright now let's jump back to our playground and let's take a look at doing this for in loop so I'm going to just create my loop right up here so for and then I'm going to use the variable name counter in right and then I specify a lower to upper range and I'm going to do one dot dot dot five and I'm going to put my braces so inside these braces we're going to put our print hello so let me erase four of them cut that one and then let's paste it inside there and we're gonna run our code boom so now we have hello five times how easy was that sure enough it's run our code from one to five now the question is what is this counter for what is this variable name for well the thing is for each iteration of the for in loop the counter refers to that number so in the first iteration of the loop counter actually contains 1 in the second iteration counter contains 2 and so on and so forth so let's say I wanted to print out the counter maybe I wanted to print out numbers 1 2 5 I could print counter and then I can run that and then you're going to see 1 2 3 4 5 output instead now one cool thing is that you see that there was this yellow warning here and that was Xcode just telling us that hey if you if you don't need to use that variable then you don't have to specify it but since we started using it in this print statement that warnings gone away so let me tell you what that warning was all about why don't we go back to hello and then that little warning is going to come back and it's telling us that this counter was never used consider and this is kind of cut off let me see if I can show you consider replacing it with an underscore or removing it so what what happens is that if you actually don't need to use that sort of counter you can replace it with an underscore like that and that's gonna be fine that's perfectly valid for in lupus index now I want to show you one more thing that might get you tripped up when you're working with loops why don't we add this to counter variable back because we're going to need it so let's say I want to display all right let's say I want to add up all the numbers from 1 all the way up to 5 and I want to get the sum of all of those numbers you know you might do something like this you might say you might declare var sum equals 0 and then remember that this counter contains these numbers for each iteration right so I might want to do something like this plus equals counter and I think this is the first time you've ever seen the plus equal operator right like this this is just an increment operator so what we're actually saying is basically add whatever counter is added to some so if sum is 10 encounter is 5 well sum is now going to be equal to 15 so another way to think about it is that it's equivalent to writing some equals sum plus counter okay just kind of just like a shorthand all right so in every iteration we're basically adding 1 and then adding 2 and then adding 3 and we're collecting it inside this variable sum so what I want to do now is just print sum and now let me run it what would you expect to happen let's take a look we get 1 2 3 4 & 5 well that's not what we expected right why is that well let's take a look so in iteration number 1 we declare a variable called sum we've set it to 0 and then we're adding 1 to 0 and then we're printing that and so we get one well in iteration number two counter is now two and then we are declaring some and setting it to zero so we're essentially adding two to zero was just two and so it prints some and we get a two and so on and so forth so the problem is that in every iteration of the loop we are declaring some and we're setting it to zero so we're not really getting that addition of the counter through the iterations like we want and if you notice you might say why am i able to declare some so many times right because in the very first lesson I told you that when you declare a variable up here like this and like STR you don't need to read Eclair it in order to assign it something else right so I can assign Tom to STR up here and that would be perfectly fine however if I try to declare STR again you know like this I'm gonna get an error invalid read Declaration of St art where you can't do that so why is it that I can do that here right in every single iteration we're declaring a variable called sum and setting it to zero well the reason is because every iteration it's almost like a clean slate there's no recollection of what happened in the previous iteration so that's why that's happening essentially we're resetting some every single iteration what we want to do instead to get the desired effect is that we should move this declaration out here and set it to zero and then inside each iteration we are essentially just adding the counter to sum and we are going to get the desired effect if we do it this way so outside here I'm gonna print some let's stop it and run it again and so we get 15 and that's the numbers from 1 to 5 all added up now as you can see up here we've declared some we've set it and down here in the for loop in the first iteration counter is one so we're adding that to zero and so sum now is 1 and in the second iteration we're not resetting in some counters to this time and we are adding 2 to 1 so we get 3 and then so on and so forth and then the loop ends after five iterations and then we print something so that's why we get a single number here so I just wanted to go through that quick example to illustrate kind of how loops behave because I know a lot of beginners who get tripped up with something like that all right recap time so use a 4 in loop to execute a block of code for a set number of times and each time your code runs is called an iteration of the loop now be sure to practice with the worksheet for this lesson because loops are powerful stuff hello and welcome to lesson 6 of my Swift tutorial for beginners video series now in the last lesson you learned about the for in loop which lets you execute a block of code for a set number of times well there's another kind of loop too actually that allows you to loop your block of code indefinitely until a condition is met these kinds of loops are awesome when you don't know how many iterations it's going to take to get the job done all right so let's dive in and see how they work so in this demo we're going to go through two types of loops that are really good to use when the number of times that you need to loop for is unknown so the first one is called the while loop and this loop checks a condition to see if it's true and then it's going to run your code and then check the condition again and then run your code and check the condition again that's to quickly take a look at the syntax for this so you start with the wild keyword and then you have a condition and then you have a set of braces and then inside the braces you have the code that you want to loop now notice that the condition is up there at the top before it even execute your code it's going to check the condition first to see if it's true kind of like an if statement if that condition is not true then your code is not going to be run at all let alone loop let's jump into the playground now and let's do a demo of the while loop so I've got this guy right here brand new playground for shot out of the oven so far let's say this counter is equal to five and then let's say that I want to let's do the same example like we did before we're going to print hello and what we're going to do is say while counter is less than or sorry while counter is greater than zero I'm gonna print hello now before I finish writing the syntax for this while loop you can see here it's telling me you need a set of braces but before I finish writing the syntax for this while loop I just want you to notice one thing so first it's going to evaluate this condition and it's true right you can see that counter is equal to five and five is greater than zero so it's true so it's going to print hello and then it's going to loop and check the condition again and it's gonna be true again so it's gonna loop and it's gonna keep looping infinitely until we get a crash there's some overflow so let me demonstrate that I would not recommend this if you've got a slower computer and I'm not even sure if mine's very fast so it's it's just gonna keep going maybe now Xcode has something where it's oh I have to run my code let's do that so you can see it just it's going bonkers right so I'm gonna stop that right now it's not stopping okay yeah it's not stopping my computer is kind of going haywire right now so what you want to do actually is inside this while loop you want to write some code to actually make it so that this condition can be false so if we print it now sorry if I can actually get this yeah so you see I wouldn't recommend you to do this but we can still walk through the code so while that's running my playground let me just explain what happened here so I basically created a while loop that ran on indefinitely until I added this code here so this code decrements the counter buy one just like you saw the other one which was plus equal one and that would actually add one to the counter this one minus is one from the counter so it starts at five right so the first iteration would be five and then print hello and then it would turn that counter into four because a decorated meant by one then loop again and four is greater than zero loops and then this line would set counter to three and then I'd go on and on and on until it hits zero and then 0 is not greater than zero so that is actually allows us to exit the loop I knew that was pretty bad idea so I'm gonna try and stop this oh there we go so can I run this down I think I broke it so I'm going to actually quit Xcode right now I think let's see what we can do here nope all right guys we're back so all I had to do was quit Xcode and restart Xcode and run my playground again so let's run it here alright so we've got our hello five times which is great now we can talk about our second type of loop which is the repeat while loop so let's let me show you where that is just scroll a little down further here the repeat while loop and let's take a look at the syntax for this so here you have the repeat keyword followed by a set of braces inside the braces you have the code that you want to loop and then what's noteworthy is that behind the closing brace you have the wild keyword and then the condition so notice how the condition is at the end of the loop instead of the while loop where the condition was at the top so essentially what happens here is that your code statements are going to be run at least once and then after it is run it's going to check the condition and if the condition is true then it's going to repeat and loop it so that's different from the while loop which checks the condition first and it might not even run even once if your condition isn't true so let's go back to the playground now and test out the repeat while loop so I am going to declare I would say counter - let's do evil five again and I'm going to use the repeat keyword and I'm going to print hello and then here I'm going to decrement my counter just like we have up there and I am going to say while counter two is greater than zero so while let me do ya help from while loop from repeat while loop and let's do that so what happens is that we get five of these printouts from the first while loop and we get five of these printouts from the second while loop all right just like we expected however what if I changed counter to let's say negative five and I change the counter to negative five and I run it well you look at that the while loop doesn't even run once right because it checks the condition first that's not true it's not gonna run your code skip this one it's going to print it out first and then it's going to realize that a negative five is not greater than zero so I'm not going to repeat I'm not going to loop so the one that you use really depends on the situation and what you're trying to accomplish if you're writing some logic that you know you want it to happen once and it only conditionally repeats then you want to use the repeat while loop however if you want your code to only be run when certain conditions are meant and as long as that condition is still true then you use the while loop all right let's recap you learned about the while loop and the repeat while loop that lets you execute a block of code and loop it indefinitely until a condition is met now the while loop checks the condition first before executing the block of code and then looping and the repeat while loop will execute your block of code first and then check your condition to decide whether or not it should repeat for another iteration hello and welcome to my Swift tutorial for beginners in this lesson you're going to learn all about functions what they are and how to use them now functions are a critical part of the Swift programming language especially if you're going to be building apps with Swift so let's get started all right so I've got a brand new playground here but before we dive into write our first function let's define what they are at the most basic level a function lets you take a block of code and give it a function name and whenever you want to execute that block of code or basically run that code you call that function name so that might seem really simple but the powerful aspect of it is that it lets you organize your code into smaller chunks of code for specific tasks so that way if you want it to perform a specific task you can run that specific function now they can get pretty powerful with the ability to give the function data to have the code take that data work with it and return the result back to you but in this lesson we are just going to take a look at the basic function so let's take a look at how to define a function first so it all starts with the func keyword or F UNC followed by a space and then your function name so you can give your function any sort of name you'd like but you should be descriptive about what that code inside the function does so that when you want to perform that task you know which function to call following the function name you have a pair of parentheses now in the basic function we're not going to have anything in between these parentheses but in the next lesson we're going to learn how to add input parameter and in between those parentheses is where you would specify those parameters for now we're just going to leave it as two parentheses with nothing in between them all right and then next up we have a pair of curly braces and then in between the curly braces is where you would define your code for that function now any code you write in between those curly braces that's going to get executed when you call the function by its name now let's go back to the playground and write a basic function so I'm going to start on the next line here and I'm going to use the keyword F UNC space followed by my function name now for this one I'm going to call it add two numbers because that's what we're going to do inside that function and I'm going to put two parentheses like that and next up I would put two curly brackets this is where I would specify the code that I want to run whenever I call add two numbers so why don't we define some constants here let a equals one let B equals two and I'll say let C equals a plus B so C equals three and lastly I'm going to print C now I'm going to run my code right here and let's come on playground all right so now it's run but as you can see there is no console output and the reason why is because this code inside this function doesn't get executed until you call the function but its name so the way you call it is you simply write the function name and sometimes you can even use autocomplete like that followed by the parentheses and if we did define some sort of input parameter here that the function will be required when you call that a function you would also have to specify that input data in this lesson for this basic function we don't have to do that all right so let's run this line of code and as you can see in the console it outputs three as expected now let's try another one so I'm going to just get rid of that line there so calling the function and I'll call this subtract two numbers I'll say let D equals five let e equals one and let F equals D minus e alright and here I'm going to print F and again nothing is going to happen until I actually call the function right so let's run the project now and as you can see there is four now this might not be immediately obvious to you but using functions is actually a huge time savings because oftentimes when you write your code for your app there are instances where you're going to have to repeat a chunk of code in different places having duplicate code in your project is generally a bad practice and something that you'll want to avoid and so whenever you see yourself having to repeat code writing the same thing that you've written before in another place then think about putting that chunk of code into a function so that you can call it from multiple places now there's one more tricky thing about functions that I want to mention to you and that is the concept of variable scope the idea is that any variables and constants that you define inside of your function they only exist and can be used within the curly brackets of that function so for example here in the add two numbers function we have declared a B and C well outside of my function that would be right here I can't let's say print a write that's gonna trigger in an error use of unresolved identifier and that's just another way of saying that it can't find what a is it doesn't know the same thing for B or C and the reason for this is because we've declared a B and C inside that scope of that function that's where it exists and likewise inside the subtract to numbers function we have de and F I won't be able to access a B or C here either I try and print a it still doesn't know what a is so we're going to get a crash if for some reason you needed your variables to be able to be accessed outside of the functions then you would have to declare these guys outside of the function now that's just something to keep in mind as you're starting to work with functions for a lot of beginners they run into issues where they're frustrated with not being able to access these variables and constants that they've declared inside their function and now you know why so just to recap you learn about what functions are and how important they are because they allow us to organize our code into executable blocks which we can then call upon to perform specific tasks you've learned how to define a simple function you learn how to call that function so that you can execute the code inside of it and furthermore you learned about the variable scope inside of a function and just to remind you about that if you declare variables or constants inside the curly brackets of your function they are only going to be available inside that function now in the next lesson we're going to build upon what you've learned here and make functions even more powerful [Music] hello welcome to my Swift tutorial for beginners series now in the previous lesson you learned about functions what they are and how to call them well in this lesson you're going to learn how to use them in an even more powerful way and that is to have your functions accept data and return data back to you when you call them alright stay tuned so in the last lesson we declared this function here to add two numbers and when you call this function it prints something down in the console however most of the times or rather sometimes we declare a function to take some input perform a specific task and then return the result to us so the first part of being able to do that is to specify that your function actually returns something back to you when you call it and let's take a look at the syntax for how this works so here's the syntax for a function that returns some data you'll notice that we still have the funky word and we still have the function name followed by the parentheses but after that you have a - followed by a greater than sign which combines itself to look like an arrow followed by a space and then the data type of the data that you're going to return from the function so if in our case add two numbers if we wanted to return the result to the function caller we would probably put int where it says data type right here because that is the type of the data that we are returning all right so after the data type you have a space and then you have the curly brackets again and you would specify your code now if you do specify a return value like this inside your function you must have the return keyword and that return keyword is used to actually end the function and return the data back to the color so now let's jump back to our playground and modifier function to return the data to us all right so we've got our function up here so we just add a - greater than sign and then we specify space the data type that does function returns and as I've said we're working with int so I'm going to return an INT so right away you can see Xcode detects hey you're saying that this function returns data but you're not using the return keyword and so we've got this error here so let's modify our function instead of printing C to the console why don't we try returning it so we just put return space C just like that all right so let's run our function now now nothing gets output into the console where where that C go right well what happens is that when you call a function that returns some data like we have in this case you have to capture that data somehow so remember variables and constants are used to keep track of data right so all we need to do is say let's define a constant let's call it sum and we are going to assign to this new constant the result or the returned data from our function add two numbers so let's run this and see what happens again actually nothing will happen because we haven't output anything to the console but let me write this print statement here so we're gonna print some and as you can see there it is in the console so what's happening here well add two numbers we're calling this function it's declaring a B and then declaring C and adding a and B assigning it to see and then it's returning C then we're assigning that result into a new constant called sum and finally we are printing that into the console using this print statement now it's not really interesting that whenever we call this function it always just returns three right so would it be cool if we were able to tell the function which two numbers to add and we can do that by using input parameters so let's take a look at the syntax for that so like I mentioned in the last lesson we specify our parameters in between the rounded parentheses now if you take a look at the screen you're going to see how we specify one parameter for our function I know that's a lot of text but we're going to jump into the playground and I will show you an example so you first start with the datatype let's start from the right hand and work our way to the left we start with the data type of the parameter and this merely specifies you know if it's an int if it's a bool you know what type of data are you asking for to be input into your function alright and take note that there is a colon in front of that and then in front of the colon you have your parameter name now you can specify any sort of name you want you're going to be using this parameter name inside your function if you want to access that data and then you have your argument label notice that there is a space in between the argument label and parameter name now what's the argument label for well it's optional and it helps your function call read more like natural English I'll show you what that means in a second for now why don't we jump back into the playground and take a look at how we specify this parameter all right so let's modify our add two numbers function up here with the parameter and before I use descriptive labels argument names and prior names I am going to just put arg here as our argument label and I'm gonna put space and then I'm gonna call this para for our parameter remember then we specify colon and then the datatype of our parameter which is going to be int and the reason why I'm just specifying the argument label and the parameter name as these is because I want you to see what the resulting function call looks like so down here you can see Xcode automatically detects that this function call is no longer correct in order to call the add two numbers function you're now going to have to specify that parameter so an easy way to do that is just to delete this and then use autocomplete again and you can see here that now the function call has this which tells you the return type of the function now if the function doesn't return any data then you're going to see void in this column instead kind of like this down here but our add two numbers function does return an end so you see int here and then you can see the parameter that it requires right here as well along with the data type all right so let's double click that or just press ENTER on that and you can see that the argument label is right there and then this int here we can put a number in there let's put 5 so now this is how you would call add two numbers with one parameter and you're basically passing in five into the function from inside of the function let's say that we wanted to assign that 5 into a we would use the parameter name we've not using the argument label we're using the parameter name inside the function here so why don't we go print and the sum should be 7 right as you can see here now what if we wanted to specify another parameter so that we can also specify what B should be inside of our function well you can specify multiple parameters you would just have to use comma in between each parameter so let's take a look at that syntax now as you can see you have a comma and then you have your second argument label then you have your second parameter name and then the data type of that second parameter pretty straightforward and you can repeat this for three four five six parameters whatever you need all right now let's jump back to the playground and specify another parameter for our function so we're gonna go ahead right here and hit comma and then now I'm going to say Arg two pair of two and that's going to be an int and now I'm going to assign para two to be and this function call will no longer be correct so I'm just going to erase that and retype it like that and you can see now I have to specify two arguments or parameters so I'm gonna say five and five and the cool thing is that let me just go back there for a second is when you let's say you're specifying the parameters you hit five you can press tab to jump to the next parameter so that's little shortcut little tip for you there all right so let's print the sum and we've got ten okay cool so let me show you some other cool things I did tell you that argument labels were optional right so why don't we go ahead and remove the argument labels here and just have the parameter name and the data type so incorrect argument labels so why don't we get rid of that and just now when you make your function call you have to specify still two parameters right because we still have two parameters but with the absence of the argument label now it writes the parameter name so let's go five and five like that right so generally when you're specifying parameters into your function you kind of want to be descriptive with them so para and para two really doesn't mean anything so why don't we change that to number one and number two and remember changing these parameter names it means that we also have to change this number one and number two and as a result this also changes remember oops okay so we can specify five and five so that's all good so far now that you notice that initially when we had the argument labels the function call was using the argument labels right but now that we've removed the argument labels from this function definition this has turned into the parameter name so if you had a need to make this read like more like natural English then you could specify argument labels to do it like that so for example I would I could say add two numbers and my first argument league label could be using and my second argument label can be end and that would become the function call would be something like that now all right add two numbers using five and five so it reads clearly and it's really understandable and inside your function when you're working with your code you still reference those parameters with the parameter name that was specified so you have number one and number two now another trick that you could do if you totally want to omit parameter names and labels from the function call and you just want to specify five and five then what you can do is instead of using argument labels like this you can just put an underscore in front of your parameter name there is a space in between that and your parameter name though so if you specify the underscores like that then your function call would look like this whoops not that one [Applause] numbers there we go now you just five and five and that now becomes your function call so just to recap you learned about what return values are you learned how to use the return keyword you learned about what input parameters are and how to specify them you learn about parameter names and you learned about argument labels and how to omit them altogether now I know it still might be confusing in your head and that's why I highly recommend that you use the exercises and challenges to practice more find all those resources in the link in the description below hello and welcome to my Swift tutorial series for beginners in this lesson you're going to be introduced to classes which is a highly critical part of the Swift programming language now I'm going to warn you it's a little bit of an abstract concept but I'm sure you'll do fine alright let's get started so in this playground here I have several pieces of information I've got three variables actually two of them are strings one of them is an int datatype remember back in lesson 2 of this series I talked to you about several common data types and I just mentioned in a brief like one second sentence that you can create your own data types well now we've arrived at that point and what we're going to talk about our classes and you can think of it as a way to organize your information now I know we talked about functions and that was a way to kind of group pieces of code together well when you think about classes you're moreso thinking about information so for example in this scenario I have a name I have a salary and I have a role well you can see where this is going all of these different variables or pieces of information have to do with a person or an employee or something like that so what we can do is we can group this information together into our own new data type called employee and in order to do that we define a new class called employee let's take a look at the syntax involved so you start with the class keyword followed by a space and then your class name in this case we would call it employee followed by space and then you have a pair of curly brackets inside your curly brackets is where you would define your class let's jump back to the playground and define our employee class so you start with the class keyword followed by space and then employee followed by space and then we have our set of curly brackets so in between those curly brackets you would put all of the pieces of information that an employee would have so why don't we take this information up here I'm going to cut it and I'm going to paste it inside of our employee class but one thing to keep in mind is that you're not defining the information for a single employee because remember we are creating a new data type here called employee so this is a general definition that you can use over and over again instead you're specifying what sort of information every employee should have so we don't fill out the specifics now we just say that an employee data type should have a name it should have a salary we could start it at zero and fill it in later and let's say for role it should be a string type as well and by just specifying two quotes with nothing in between them it's just an empty string so just like that you've defined your new class which is essentially a new data type it's called employee and every single employee is going to have a name a salary and a role now here's the part that is going to get really tricky and you really have to wrap your head around that and that is that your class that you've defined right here is kind of like a template so now that we've defined this class how do we use it well let me show you some examples with some previous data types that we've worked with before first so let's say we have a equals 10 and let's say we have B equals Ted and that will suffice so what's happening here with this line essentially we are creating a piece of data 10 right it's going to be stored in memory and then we're creating a constant called a to keep track of that data in memory same thing happening right here Ted is a piece of string data that we are creating in memory and then we are creating a constant called B to keep track of that data in memory now the same concept applies here with our new data type we're going to create a new employee in memory and then we are going to create a variable or constant called C let's say to keep track of that employee in memory so let me show you how to create a new employee in memory well all you have to do is write the class name followed by two parentheses like that and by writing this statement here we are creating a new employee data in memory so why don't we create a new constant and assign it to that constant now this employee data that you've created in memory is called an object also known as an instance of the class in this case that is an instance of the employee class so let me show you just to drive home that this is your own custom type when you create a constant a that would be like that you know you're defining the data type of the constant right and this would be that now a and B are really simple data types right integer and string however C is your custom type right it's employee and inside contains this sort of data here and right now it's all it's set to these default values which you have specified but we can actually access that data inside of the employee and we can set and we can also get that data and the way we do that is using something called dot notation so let me show you how it works so down here since we've created a new employee object and assigned it to C let us change this to var actually because we will probably be modifying it so we write C which points to our employee object and we hit dot on our keyboard and that lets us access all of that data inside of the employee class so we have name we have role we have integer so why don't we set the salary to a thousand or first yeah let's do that and then I can show you print C dot salary and you can see that it says a thousand right there I can also set the other pieces of data like that you know something like that now another cool thing about defining your own data type using the class like that is that in addition to specifying what sorts of pieces of data it should have you can also define functions in here yes you can write F UNC space let's say do work right if you forget this is how you define a basic function here and I'm just gonna print I'm doing work or something like that and then let's say because they are doing work we are going to increase his salary by one doing work gets you noticed by your boss which results could result in a promotion and you would get more salary so that's at least my line of thinking right now so let's say that that's the case how would I execute this function if I just try to call the function do work like this it's not actually going to be recognized because this function is part of my employee class I would actually have to call this function on an object of that class because I've created an employee object right here and assigned it to see I can actually do C using dot notation now and you can see that I can access this function actually why don't we change our print statement here and insert the name let's say but why would you refer to yourself in the third person it's doing work how about hi my name is and I'm doing work I don't think I'd hire someone like this who refers to some themselves like that let's see what happens okay all right it's running all right hi my name is Tom and I'm doing work so that's pretty cool now I want to show you something else so I'm going to define another employee I'm going to create another employee object in memory and I'm gonna set this process name to Sarah and let's say Sarah is a sa manager d dot salary equals do with that oh this is an integer and I am going to say d dot to do work now you'll notice that C and D are two separate employee objects when I'm modifying the data for D it doesn't affect C and vice versa and when I call the do work function on D it has nothing to do with the do work function for C so that's a basic introduction of how to use classes so one last thing I want to mention is that when you declare a function inside of a class it's actually called a method of that class and these variables that you're defining inside your class are called properties of that class and also I want to point one thing out is that notice I can access salary from inside my function and that is because it's declared up here all right so properties and methods when there are inside classes now there's a lot more to classes but I just wanted to introduce them to you in this video I hope you can see why classes are a fundamental building block to organizing your information now in the next lesson we're going to take classes even further hello and welcome to my Swift tutorial series for beginners in this video you're going to learn about inheritance otherwise known as sub classing which allows you to create a class which builds upon or extends from other classes which have already been defined now this saves us a lot of time and effort from defining classes that do similar things alright so stay tuned I don't know if you've noticed but now that we've talked about functions having the ability to organize your code into chunks and then classes being able to organize and group variables and functions together in the way that makes sense these are all different ways of organizing your code now today's topic sub classing is another way to further organize your classes so remember what I said about duplicated code and how it's a bad practice to have duplicate code all over your project because that makes it hard to maintain and hard to manage hard to make changes now when I introduce functions I told you that having duplicate code all over your project is a bad practice and it is and functions were a way to address that you can define a function and then you can call it from multiple places when you need to execute that piece of code classes are the same thing sometimes you might have to define two classes which are very similar so instead of having two very similar definitions or classes you can use sub classing and have one cost extend from the other so that's what subclassing is all about let's take a look at an example using the playground that we had yesterday we had to find an employee which had a named salary and a role and a method called do work now remember these are called properties of the employee class and this is called a method of the employee class now let's say that I wanted to create another custom data type called manager right so I would define a manager class like so right now a manager also has a name right so I can go ahead and define that managers also have salary and roles and they also have they also do work so you know I would just be defining the same thing very close to it all over again now instead of doing that what we can do is have the manager class be a subclass of the employee class so we can define that or we can do that by putting a colon after manager and we can specify employee and that is basically saying that the manager class inherits or is a subclass of the employee class and this also means that the manager class automatically inherits all of the properties and methods of the employee class so let me demonstrate for you so let's say let M equals let's use var M equals a new manager object so I've just created a new manager piece of data in memory and assigned it to M I can say you can see here Maggie maybe she's got a bigger salary role of manager of IT or something like that right and M can do work so hi my name is Maggie and I'm doing work now let's say as a manager you also want to keep track of the size of the team that the manager is managing so for the manager class we could have another property called team size you know and we can start that at zero but now for my manager object down here in addition to all of these properties and methods that it inherited from the employee class in addition to that it also has you know the properties that I've defined inside the manager class so I can say the team size is 10 now essentially I was able to create a new class based off of an old class right and add additional functionality to it now you can also modify existing function so let's say that you know when a manager does work it's he or she is not just doing work he or she is managing people so what we can do if we wanted to change the definition of do work we can say we can redefine it here after using this keyword override so I'm gonna override the do work method and I am going to print I'm managing people very important right and the salary increase Wow it's going to increase by two all right so now when I run this if not going to say hi my name is Maggie I'm doing work it's going to take this overridden function right because M is a manager so that's why we get down here I'm managing people but did you know that if you wanted to instead of replacing the functionality of that inherited do work method you let's say you just wanted to increase the functionality you want it to add to it so what you can do inside here after overriding it you can call the do work method of the employee cost from here all you have to do is write super dot and you can access these properties or you can call the do work method so now when I write M do work what it's actually going to do it's it's going to execute the do work method definition from the employee class and then after that it's going to do this additional code that I've written here so let's run our project and see what that looks like you can see hi my name is Maggie and I'm doing work and I'm managing people the reason why this keyword is called super is because the class that your sub classing from is also known as the superclass or the parent class so for the manager class employee would be the superclass or the parent class and that's why the keyword is called super alright so in addition to being able to redefine the methods of the superclass I can also declare new methods so I can say you know fire people oops what's going on I'm firing people so now I can say m dot fire people but you know if I let's say declare a new employee here just to demonstrate using dot notation on the employee object you can see I only have those things which have been defined in the employee class so that's how powerful sub classing can be it can really save you a lot of work you're not gonna have to redefine two different things that are very similar what we've got right here is actually one level of sub classing or one level of inheritance but it can actually go much deeper than that for example an employee is also a person right and all people have names so I could for example declare another class up here which contains the name property right because all people will have a name and you know so then inside the employee class I wouldn't have to define that and instead I can go that the employee is a subclass of person right so you can build these hierarchies in these trees and it's really a way of organizing your data and your information now inside of your classes you're organizing your properties and your functions so now you can see holistically how all of these things are starting to come together variables functions and classes okay so this was a simplified example of sub classing but it's essentially how it works and it's very predominant in the Swift programming language as you're going to see in the next lesson as you can see sub classing helps you save a lot of time by allowing you to define your new classes based on what already exists and then improving upon that or customizing it a little bit without having to redefine everything all over again hello and welcome to my Swift tutorial for beginners in this video I want to introduce you to UI kit which is an apple framework that contains a lot of the classes we're going to need in order to construct iOS apps all right so let's dive in and see what's available in UI kit so if you imagine most apps there are common elements between all of them such as labels buttons maybe text fields images and if we were to build each of these components from scratch every single time we've built an app it would be very time consuming and a lot of wasted effort and so Apple has provided us a library of all these pre-built elements that we can use in our apps and they've called this library UI kit that's what we're here to discuss now UI kit contains a lot of user interface elements and I know it strays a little bit away from Swift programming which is what this series is about but one of the very interesting things about UI kit which is relevant to what we've been talking about is how they use inheritance and sub classing to create all of these different UI kid classes so I'm gonna go through that with you as well but first let's take a look at where you can see the documentation for UI kit so if you just type into google apple space UI kit into a search it should be the first result when you click on that you're going to get to the reference page or the documentation page for that and then you scroll down and you can see all of the different things in UI kit you can see it doesn't just contain user interface elements but it contains other things like classes for animation touches gestures dragging job and stuff like that another really handy way to explore UI kit which I recommend even more is just to open up Xcode if you go under window you should see developer documentation and that's what you want to click and bring up on the left hand side under Swift you're going to find UI kit near the top and it's much easier to browse this like that one of the things that they have removed is kind of a hierarchy that shows you how each of the classes are subclasses of other classes above it and so I wanted to pull up that diagram for you to illustrate how they're using inheritance and sub classing and so I googled it and I found an old image from back then that shows you how each of the elements derived from other elements and all the way here on the right hand side you're going to see this UI button here and this is your classic or standard iOS button that you would put in your view but notice if you follow the lines that it's a subclass of UI control which is a subclass of UI view which is a subclass of UI responder which is ultimately a subclass of nsobject so it's very interesting to see if you are curious about what any of these classes do you can go into this documentation which I showed you here let's say we go under button great you can see the declaration here class UI button that it's subclasses from UI controls just like we saw over there in that hierarchy but if you click that UI control it's gonna bring you to that class and you can read about it as you can see it's the base class for controls which are visual elements that convey specific action and response to user interactions pretty cool but down here you can see that UI control is actually a subclass of UI view so we click on UI view and see what that does it is basically something that you can put on the screen for the user to see now UI view is actually a subclass of UI responder what's that click into there is an abstract interface for responding to and handling events which explains why so many user interface elements are ultimately a subclass of us responder but UI responder itself is a subclass of nsobject so what's that click on that the root class of most objective-c class hierarchies and we're gonna talk about that in a second why that says Objective C from which sub classes inherit a basic interface to the runtime system and the ability to behave as objects so it's basically what makes an object tick if you will and the reason it says Objective C is that originally before Swift the language to build apps was Objective C so a lot of UI kit is actually still written in Objective C with Swift being a layer on top where you can use these classes as Swift one of the dead giveaways is this NS prefix in front of the class name usually when you see that you can expect that that is an objective-c class however whether that's objective-c or Swift that's not what I wanted to point out to you in this lesson right here what I wanted to show you was eight how Apple has created this whole UI kit library from all of this inheritance and sub classing and that's really cool to see how they organized all of the different pieces there and then B to let you know that there is this UI kit library at your disposal with so many pre-built components that you can use to build your app now once you finish the Swift programming series and you move on to learning about Xcode and building user interfaces and stuff like that all of these classes are going to come in handy all right so at this point that's all you need to know about the UI kit library I'll see you guys in the next lesson hello and welcome to my Swift tutorial series for beginners in this video I want to talk to you about initializer methods for classes these guys exist to make sure that when you create a new object of your class that that object is ready to go plus you can customize these initializer methods to set up your object in any way that you want when you create a new object from your class all right so let's get started and see what that all means so what I've got here on the screen is the playground that we created back in the classes part two lesson when we're talking about sub classing just to remind you we have a person class and then we have an employee class which is a subclass of that person class and then we have a manager class which is a subclass of the employee class so now that I've jogged your memory about what we have here why don't we create a new person object do you remember how to do that first of all you use the class name followed by two around in parentheses right let me show you let's do it here person two rounded parentheses and just like that we've created a new person object well what you might notice is that this kind of looks like a function call right remember to call a function you write the function name followed by two rounded parentheses and in any input parameters in between those parentheses in this case right here a person with these two around in parentheses you actually are calling a function of that class now I know that might seem weird because if you scroll up to the top here we don't have any functions that cleared in the person class right well there's actually a initializer function that is default to all classes that you don't have to declare and let me show you what it looks like because you can explicitly declare it so if we were to explicitly declare the initializer function of the person class it would be using the keyword in it followed by two rounded brackets followed by these curly brackets and you can put any sort of initialization code you can here let's say custom init code also notice that for this special initializer function you do not need the F UNC keyword that we normally use to declare functions this is an initializer function so let's say for example I put in here that I want the name property to be Joe right and now if I create a new personal object I say let my person equals new person object what's actually happening here when I call this it is creating a new personal objective but it's using this init function here right and it's actually setting this it's running this custom code so to prove it to you why don't we print out the name right after creating that object so you can see here it says Joe as the name now the initializer function is useful for you to put any custom code you want in there to setup the object if you don't specify an init function at all like what we had before then it's still there you can still create new objects from that class and that's actually what the purpose of the initializer function is for it's to set up a new object of that class you know allocated memory do whatever it needs to do to return that object to you ready to use now here's the interesting thing about initializer functions so we can have our basic one but we can also have different ones which accept parameters for example let me show you this week an acceptable name let's make it a string like that and then we can also have our basic one that we had before like that so we can have multiple initializer functions let's go back down here now I can create a person object with the basic initializer function which doesn't do anything and when I run this code it doesn't print anything out because I haven't written anything in that init function however don't forget that I created another one which accepts a name so this time I can put in a name like that and if I print it not doing anything right now did I oh did I do it yeah my bad I didn't do anything in here so now what I wanted to do inside this initializer function was to set the name property to the name input parameter that got passed in here now I could write something like this where I'm trying to set this property right to the name that gets passed in but as you can see it's a little bit ambiguous Xcode is telling you that there's an error but it's not recognizing that I'm trying to set this property it thinks I'm trying to set this parameter to that parameter so what you can do in this case to resolve this ambiguity is to use the self keyword so you can write something like that self dot name and when you do this this is referring to that object's name so this is basically referring to this property here and now this name is from this parameter so it's very clear what you're trying to do here all right so let's run this code again and you can see that this time it prints tom now let me ask you another question since the employee class subclasses the person class that means that the employee class also inherits all of its functions from the person class right do you think that this employee class also has these init functions why don't we give it a try go back down here let my employee equals employee and as you can see the employee class does have this init function that it inherited from the person class so I can use this with the employee class as well so that's pretty cool now I want to talk about overriding init functions you know just like how we talked about right here where the manager class overrides the do work function of the employee class and then it calls superdude work which is going to execute the employees do work function as well as you know any code down here the same thing applies for init functions so let's say that we have in the person class we have this init function right where you pass in a name let's say for the employee class I wanted to do something extra I wanted to override in it so we're gonna override the same function from the person class you know we're overriding this guy right here I also want to initialize the role so I'm gonna do self role let's default everyone to analyst or something like that all right everyone starts off at the analyst level however what I can do is call this person's or sorry and I call the super classes init function and pass the name into there so this this is calling and the init function of the person class this is additional init code all right so now by calling this an it where I pass in the name of the employee like if I print my employee dot role and my employee dot name so you can see that it's set to analyst and it's set to Jo here so what I wanted to demonstrate here was that even within it functions you can use to override keyword and provide a custom implementation of that initializer function and then also call the super classes implementation as well so I hope that was clear if it's not just leave a comment below and I'll be happy to clarify things for you alright later on we'll dive a little deeper into initializer methods and we'll talk about how there are two different types one called designated and one called convenience initializers [Music] hello and welcome to my Swift tutorial for beginners in this video I want to tell you all about optionals which are probably one of the most confusing topics for beginners if you've ever looked at Swift code and come across exclamation marks or question marks then you've come across optionals so let's get started and find out what they're all about so to demonstrate what an optional is let's first take a look at how we've been declaring our variables and constants as we remember whenever we declare a variable we use var and then we use some sort of name let's just say a for this example and up until this point you've always seen me assign something into my variable declaration something like this or whether I declare you know a string I'm always assigning a piece of data into my variable declaration or constant declaration right away now there will be instances when you're building apps that you may not want to assign data to your variable right away you might just want to declare it but if we try to do that let's erase this assignment statement and you erase the data as well and just leave it at that you'll see that Xcode really doesn't like that and that's because it wants to make sure that all of your variables and constants actually are keeping track of some sort of data because that's the purpose of their variable and the constant right well using optionals you can create a situation where you declare a variable or a concept without assigning something to it first in which case it is empty so how do you define emptiness well there's actually a type for empty and it's called nil and it's simply a keyword like that and il which stands for empty or nothing now if we don't want to assign actual data to our variable first we can assign it nil like that right and that means that that variable can it's nothing however as you can see we're still having some problems here remember I told you about data types for variables and how variables can only store data of a certain data type and you can explicitly state the data type of that variable and if you don't then it's going to take on the data type of the first piece of data that you assign to it so for example for a if I did that then it would take the data type of my integer and it would determine that a should have the data type of int in the case of nil however there is no data type for empty and so variable a really doesn't have a data type right now and we have to give our variable a data type so in this case if you're going to assign empty into your variable that means you don't want to put any data into it yet we have to explicitly put a data type now let's go ahead and put int right and for this one let's put string like that let's run it as you can see there is still a problem because the int data type doesn't include empty in fact none of the data types include mil as a valid value they nil is not a valid integer and nil is also not a valid string so that's why we can't assign nil to an integer variable and we can't assign nil to a string variable well this is where optionals come in by adding a question mark to the data type like this this becomes an optional integer which means that it could either be an integer or it could be nil same thing goes for this right here the data type is now it's not string it's an optional string which means that it could contain a string object or it might contain no so that's the gist of an optional in order to demonstrate how to work with optionals I'm going to use another example so let me delete this for now and then let me grab a piece of code that I prepared for you let me just run the project here make sure that it runs as you can see here I have a class called Christmas present and this class contains a function called surprise which returns an integer now this integer is going to be a random number from 1 to 10 so why don't we just use this code here let's use let present equals let's create a new Christmas present object using that remember initializer functions right and then we want to activate the surprise so sorry present dot surprise and then we're going to print the output of that function so let's run our code and we get 5 in our console right here so that's the surprise now this data type of this constant right here if I explicitly declare it would be the type of my class right next why don't we make this an optional type by adding the question mark there and then let's say that we put nil in there you can see here that there is an error Xcode says that the value of optional type Christmas present must be unwrapped to refer to the member think of member as function or property must be unwrapped to refer to the function surprise right and the reason for this is because I told you with an optional datatype this constant could contain a Christmas present object or it could contain nil and in this case we do know that it contains nil so what that means is that you have to check that optional constant or optional variable to see if it actually contains an object or if it contains nil before you access any of its functions or properties because you can't call a function on empty right you can't access a property of nil so what we have to do in this case is just double check that the constant present actually contains an object a Christmas present object to be specific before we call the surprise function on it now there are several ways of checking an optional type to see if it's nil before using it and I'll demonstrate some of them let me erase this line first so we are going to check the optional to see if an object exists or if it contains an object let's say it like that so the first thing we can do is basically compare it to nil with an if statement so if present is equal to nil if this is true then it contains no so don't do anything with it else it contains an object right now the reverse of this is also true you can check if present not equal to nil right and if it's not equal to nil then it contains an object so why don't we use this statement here because we want to only call the surprised function if there is an object and we don't really need to do anything with it if it is a nil so why don't we erase this one here and let's use this one so it contains an object now call the surprised function now since I have already checked that it contains an object I should be able to just call surprise right you'll notice that Xcode has helped us put this question mark here because that's what it thinks you want to do but I'm going to erase it because I want to demonstrate something for you see if I try to run this there's an error because you see with an optional variable or an optional constant before you can actually access the value inside that optional datatype whether that's a natural object or whether that's nil you have to unwrap that optional now I know that's a weird term but a good analogy or a good metaphor to think about an optional variable is that it's like a Christmas present or it's like a box and you don't know what's inside of it it could actually contain an object or it could be nil but you're never going to know unless you unwrap it first you open that box to see what's inside now right here you you might say hey we've already checked that it's not nil right so this check is kind of like taking that box and just shaking it and listening to it you know when you're a kid trying to find out what's inside your present that's what that's like and all that does is that it tells you if there's something inside I mean if it's nil you're shaking it this it's not gonna sound like anything but if there's an actual object inside and you shake it you'll hear something so this check right here lets you know that there is something inside but that doesn't mean that you can access what's inside right until you unwrap it so let me show you how you can unwrap that variable and get at the object so that you can call the surprise function on it all you have to do to unwrap this optional variable is use the exclamation mark after it and what that does is that tears open that box and you get whatever's inside whether that is the actual Christmas present object or whether that's nil so because we've already checked here that it is an object I'm gonna say dot surprise and I can print that right so let's run the statement here actually nothing is going to run do you know why because it's actually nil right so our if statement actually worked so this if statement said if it's not nil right then unwrap it and then call the surprise function on it but since it is nil it didn't do anything so why don't we change the statement why don't we actually put a present inside the box so now when we run it we're going to get the random number surprise which is 6 so now you know how optionals work but I mentioned there are a couple of different ways of checking right to see if there's an object inside of your optional so this is one way another way is called optional binding and this is a little bit more advanced than that basic check there and it's kind of another way of writing an if statement so you say if let say actual present equals present then we will print actual present dot surprise so let me explain this statement right here it's still an if statement so you're checking something you're actually checking to see if present this optional variable to see if it's nil or not if it is nil then it's just going to pass through this if statement and not execute the stuff inside however if this optional variable does contain an actual object then it's going to assign it to this constant that you're creating right here called actual present so it's almost like two statements in one the if statement checks to see if it's nil if it's not nil then you're gonna assign the actual object unwrapped into actual present this constant and then you can inside that if they mean you can use actual present as the actual object because what it will do is that it's going to take the unwrap object and assign it to actual present ok so you don't have to do any unwrapping here and you can just call surprise so you'll see six and four four was from here and six was from here alright last thing to show you about optionals is another thing called optional chaining now this is what you saw a little earlier when Xcode tried to put a question mark there so let me show you what that is so you put a question mark next to the optional variable and then you call your method like that so with optional chaining you can see we don't have any if statements or anything like that but basically what this does is it checks to see if this is going to be nil or if it actually is an object if this is nil nothing happens you're not going to call that function however if there is actually an object in there then it's going to call the next part on that object so in this case it's going to call the surprise function on the actual object because there is an object in that optional so that's what's known as optional chaining so why do we even have optionals and Swift well the reason is because Swift is a type safe language and what this basically means is that Swift forces you the programmer to be very specific about the types of data that you're working with in your code and in the long run this actually helps you because it forces you to think about things thoroughly such as if this variable will need to contain nil or if it's always going to have a value and also how we're restricted to a certain datatype for a variable or you're not going to accidentally assign another datatype to that variable because it is type safe so I just wanted to revisit some of the ways of declaring our variables and constants with optionals now because there's one thing that I haven't shown you yet and that's what I'm going to show you now so in here line 3 you see kind of the standard way where we declare a variable with the type and then we assign data to it and you've also seen about how you can add the question mark after the data type to turn that into an optional type and you can assign nil into it well you can also just do this and that's absolutely fine because when you declare an optional data type like this from variable C by default it's going to be nil so you don't actually have to explicitly assign nil to it so when you're declaring optionals I would recommend that you do it this way there is also another type of optional that you can declare and that is using the exclamation mark now I know in this lesson I showed you that putting an exclamation mark is unwrapping that variable or constant to see what's inside the optional right well this is called an unwrapped optional so this allows you to D can store a string or nil but it is already unwrapped so you don't have to unwrap it but it can also store nil C in store a string or nil but it is wrapped so you have to unwrap it in order to see the contents whether it's nil or the actual string so when would you want to use this sort of optional vs. this one well I would say in general you would want to use this one because it provides that sort of type safety checking that Xcode has so when you try to use C in some weird way and you're not checking against nil Xcode is gonna warn you hey this is an optional so you you might have to check for nil before using it you might not be able to call this property or this method on C because it might be empty so it provides you all of those warnings which makes you a better programmer and it makes your code more robust than it will probably crash less so if you use this instead you can also store nil or values in here so it gives you that flexibility but it's not gonna have any of that type safety checking so Xcode is just going to assume that you know what you're doing it's not gonna warn you that it might be nil because it's already unwrapped right but just know that deke may contain nil so it's it's almost like you are driving without a seat belt maybe that's a bad example but hey because there are places where you might want to use this you know for sure that only initially it may be nil but then after a certain point you can always be sure that there's a value then maybe it's safe to use that and then you can ignore all of that sort of optional binding optional chaining all of those checking for nil you can save all of that code however if it's a variable which may contain the value in the nil and then that value might get erased so it's nil again and it keeps flipping back and forth then maybe having it as this sort of optional is better because then it forces you to remember to do that checking so I just wanted to give one more quick example about these two kinds of optionals using our Christmas present class so why don't we declare a new Christmas present like so let's say present one is equal to well let's declare the type of this so we're going to declare a new Christmas present optional like so and we're going to assign it nil right and then we're going to do Christmas present too and we're going to use this and remember we don't actually have to assign it to no but I'm going to write it anyways just so it's very clear to you what's inside these variables right here so if I wanted to let's say do present one dot surprise like that let's remove the optional chaining you know we get that sort of type safety checking it's saying that it's an optional it might be nil if it's nil then you can't call surprise on it so make sure you you know you do sort of checking however if I do present to dot surprise you can see that let me just show you can you type it out you can see when I do that there's no sort of there's no optional chaining there there's no you don't have to unwrap it at all or anything like that it just treats it as an unwrapped optional you can just use it as is and you're not going to get any sort of warning so I'm gonna run this but now you get an actual app crash so you know if this goes unchecked and you launch your app and the user is using it then you're actually getting gonna get an app crash which is really bad whereas if you did it with this sort of optional you know even as you're running it you're gonna get a warning from Xcode forcing you to fix that and address that before actually shipping your app or even allowing you to run your code so like all the other things we're learning about Swift we can go deeper there are additional things that you can learn about optionals but this is your introduction and I just wanted to tell you what they are and a little bit about how to use them practically speaking you'll be using them most of the time like how we covered in this lesson in the future will cover more of the complex aspects of optionals also you might be wondering why and when we would use optionals but let me tell you you will definitely come across optionals when you're building apps and when we get to building our apps together now you'll know what they are and how they're used because you've watched this lesson hello and welcome to my Swift tutorial beginner series in this video we're going to talk about properties which you've been using already ever since we introduced them in our classes lesson however in this video I'm going to go through some additional things that you can do with properties all right so let's get started so before we start one thing that I wanted to point out to you just in case you didn't notice is about property scope so remember back when we talked about functions and talked about variable scope and how if you declare a variable inside of a function you're not going to be able to access and use that variable or constant outside of that function you can only use it within that the curly brackets of that function so each function has its own variable scope but when you declare a class like we have for example here these properties that we declare up here they're kind of just like variables that are at the class level so because they are declared up here at the class level they are accessible and usable by any of the functions inside that class so for example here you can see our do work function or method sorry if a function is inside of a class it's called a method remember so in our do work method of the employee class here we can access the salary property because it's declared up here and if we had more methods in this class inside each of them we would be able to access the salary or the role all right so that's just one thing I wanted to get out of the way in case that wasn't clear one cool thing that I want to talk to you about declaring these properties up here is that aside from them just being variables at the class level there are some unique things that you can do with them for example let's take this manager class right here let's say that we wanted to create a bonus property that would basically determine how much of a year-end bonus this manager would receive as part of their compensation so let's create a new property called bonus however and you know this is going to be an int type however the bonus is actually tied to how many people they manage so you could do something like this for example maybe in the initializer function of the manager class you could say that the bonus property equals let's say team size times a thousand so you get an extra thousand dollars for each team member that you manage right so you could definitely calculate that in the initializer function of the manager and set that property however there are something called computed properties and that allows you basically to make your property a calculation so instead of having to explicitly assign a thousand times team size to the bonus property you can just make this bonus property a computed property so to do that you would declare your property and you have to specify a data type and then you have your curly brackets and let me just write a comment here this is a computed property one it's accessed the code in here will run then we'll return the value so here we can say return team size times a thousand and literally as simple as that so the bonus property is calculated via this calculation here it's a problem right now is that the team size is zero so we need to be able to specify the team size why don't we set that as part of the initializer function so we could we don't have to over I let's create our own one which takes in a name but it also takes in a team size which will be an integer alright so this is our own custom initializer function for the manager class however because the manager class is a subclass of employee and it inherits all of the employee classes methods and properties we have to make sure that all of those are initialized properly to so the way we do that is we can simply call super init which is basically calling the init function of the employee class so we're gonna pass in the name this calls the init of the employee class additional and it work here we will set self-thought team size equals team and because you know the parameter is a different name from the property we technically don't need the self we could just do that and it's very clear what we're trying to do but you it doesn't hurt to add the self as well just be consistent in your coding alright so now let's try to create a new manager object and then try access this bonus property so down here say let M equals manager we're gonna use our new fancy init method let's call her Kate and the team size is let's say 11 all right let's print out what would her bonus be let's run this code and it is 11,000 so that's pretty cool now there are additional things that we haven't covered in this lesson such as getters and setters and property observers but we'll have to do another lesson on properties later on for now this is a great start hello and welcome to my Swift tutorial series for beginners in this video we're going to revisit initializer methods and I'm going to tell you about designated versus convenience initializers so let's get started so here I've got a person class and all it has is one property called name which is initialized to the string none remember when we talked about classes and default initializers all classes will have a default init initializer that's why I can create a new personal object like this it's actually calling the default initializer now I told you that the purpose of the initializer method was to make sure that that object is set up and ready to go now in addition to allocating memory and doing all of the other things that it needs to do to create that object and return it to us another job of the initializer method is to make sure that all the properties of that object are initialized and let me show you what that means right now so for example in this person class I have a name property it's initialized with this piece of data none now let's say I create an optional let's say not salary let's say net worth or something like that and let's make this an optional integer and that is also already initialized to nil because remember I told you that by default the value is nil for optionals now I can also say gender let's make this an optional string that is already unwrapped now this is also initialized to nil so right now by default all of the properties of the person class are already initialized so that's why I can create a person object like that without a problem but let's say that one of the properties is not initialized now let me show you what that looks like for example for name I can say that it's gonna be a string type but I can not assign it any value right then it's gonna start to complain and say that hey your person class needs to have an initializer explicitly where you initialize the name property so in this case what we do is we do a knit and then we assign a value to that property right because this is not an optional right if it isn't optional then that's a different story it it is initialized to nil but when you just say that it's a name property and it should contain a value right this is the string datatype it should contain a string value and you're not assigning a value to it then it falls on the initializer method to give it a value before that object gets passed back to you when you create a new person object so I can show you let's say let a equals new person object and then I can print a dot name I can show you what that is right it's none because when we create this new person object it's calling this initializer and it's initializing this name property to none you can also try to print a net worth for you and you'll see that it's going to be nil now these initializer methods which ensure that all of the properties are initialized you know we're just calling them initializer methods but the proper name is designated initializer and these designated initializer methods can be guaranteed to return that object to you ready to use all of its properties initialized so on and so forth now there's another type of initializer method called a convenience initializer so these convenience and initializer methods are for you to kind of preset some of the properties of that object based on what you need and then that convenience initializer should call a designated initializer just to make sure that all of its properties are set so let me give you an example of what that what that looks like so let's say that this is our designated initializer right because because it makes sure that all properties are initialized and it's ready to go now I can create a convenience initializer by using the convenience keyword like that and let's say I want to create an initializer to create a rich female so let's say that you need to pass in the gender and you need to pass in the net worth or it should be a rich person in general right then I would first of all I would need to call V in it right call the designated initializer to ensure that the object is ready to go set any other properties or custom code to initialize for this scenario so I can say you know self-taught gender is equal to whatever gender was passed in and self-thought net worth is equal to I forgot to put a type here so let's say that's int all right miss myself all right all right so this is creating a new person object creating a new rich person object that B equals person and I can use my male let's change that to male that right so this convenience initializer just gives me an easy way to create a specific type of person object initialized through some sort of whatever values that I need but it calls the designated one because this is kind of like the steadfast anchor initializer that makes sure that all of its properties are initialized so you can count on it as sort of like the go-to initializer so just to recap designated initializers are those that guarantee all of its properties are going to be initialized and that that object is ready to go for you whereas convenience initializers are optional and they basically give you an opportunity to create an object but preset it to the values that you need like what we did in this case but convenience initializers must call a designated initializer as well just to make sure that everything is set up and ready to go so you can see that we did it here in line 16 so that's the difference between a designated versus a convenience initializer method [Music] hello and welcome to my Swift tutorial series for beginners today you're going to learn how to manage a collection of data in what's called an array if you're working with many pieces of data it's going to be hard to manage them all using just constants and variables so let's take a look at how a race can make our life easier alright stay tuned so Swift has a couple of collection types that you can use to manage your data easily and the one we're going to talk about right now is called an array and this is a collection type that is ordered by indexes and that means that there is a specific order to this list of values so you can see here in this demonstration or this example it starts at 0 and then it goes 1 2 3 4 and so on and so forth and at each position there is a value or a piece of data so there is a defined order and that's really important to know let's jump into the playground where I can demonstrate and need and an example of how to use a race so right here I've got three variables a B and C and let's say that I wanted to change these strings to my dog my cat and my bird well I can go about it this way and say something like this I can just add the word my with a space to a alright so a is dog I'm gonna add my in front of it and reassign it to 8 so that would be my dog so I could repeat this with B and C but I mean this is only an example with 3 items let's say we had a hundred or 200 items then that would be very very tedious right what I could do is also I can put these values into an array and what that looks like is it starts with a pair of square brackets and each item in the array is separated by a comma so I would have dog comma cat comma and then bird so there's no comma at the end it's only in between the actual items so this is an array of 3 items with dog starting at index zero cat at index one and bird at index two so just like what we saw here yeah dog cat and bird that is our rate so having this array is great but we need some sort of way to reference the items in the array so why don't we assign this array to a constant called my array and in order to access these items all I have to do is say my array and then use my square brackets and then put in the index of the value that I want so if I want a dog I would put in index 0 so it's print that and we can see dog if I wanted bird I would put in index 2 right because it starts at 0 alright so in that case I could do something like this my array 0 is equal to my space my array 0 kind of mirrors this statement right and this shows you that you can use this sort of same syntax and there's actually an error here this is a really great example because I'm trying to assign something into my array at index 0 but this is a constant so I can modify it after it's a sign so I actually need to do variable like that let's make my array a variable all right so this is great because it shows you that this syntax is to retrieve the item at index 0 but I can also assign things into index 0 using this assignment operator like that right so the resulting value at index 0 is yes that my dog right but this isn't very efficient either I mean I'd have to write this line three times or however many times for you know however many pets I have so this is where it gets really powerful because you can use loops we learned way back then in conjunction with a race so let me show you how that works so for example let's use a for loop or a for in loop I mean let's say there's a counter in 0 to 2 all right so now I can say I can well why don't we just print it out for now so we can print out my array and then let's access the index I can put in counter in there so let's see what that looks like if I run this code see I'll print out my dog cat and bird but actually it's because this line modified what was at index 0 so let me get rid of that line and let me print this again so you can see dog cat and bird it's merely printing out each index of that array but already this is really powerful right because we have one line of code and it's being looped three times but each time it loops it's doing something different what if we did something like this what if we did my array counter is equal to my right space plus my array counter all right now we're talking because what we're doing here is each iteration of the loop we are accessing that index and then we are adding my in front of it and then we're reassigning it to that same index basically changing the value and then we're printing it out here so if I had 200 items in my array I would just change this to 199 right and that's very little code compared to what we were doing up here right so you can start to see how powerful it is to use arrays with loops now what if we didn't know the range of the array right right here I'm assuming that I know there are three items in here that's why I'm doing this range zero to two well the array comes with some handy properties that we can use one of them is called count which returns how many items are in the array it always starts at zero so we're gonna start at zero if we want to access the first item in the array however we are actually we can use the count property of the right so we can do my array dot count but they're gonna run into a problem with this let me show you why so if I run this code you're gonna get my dog my cat my bird and then index out of range whenever you see this error index out of range you start to think this error message means that we're trying to access an index that doesn't exist in that array it's out of the range of the array well why is that because my array dot count returns the number of items in there right right so what it returns three so our loop actually goes from zero to three inclusive so it's gonna start at zero it's gonna do one and it's gonna do two and then it's going to do three and there is no fourth item in our right right this is 0 this is 1 this is 2 and when it tries to access index 3 there's nothing and that's why it crashes and gives us this error index out of range so what we actually have to do when we're working with arrays like this and we want to basically use this count in a loop we have to do this minus 1 and then that's going to go from 0 to 2 essentially now it's really good that you know about the count property now of the array because that's really useful but there's actually an even easier way to write this for loop we can do something like this for each item in my array do something with it and that's really the easiest that you know the easiest that you can get so you can do you know if you need the index for some reason and you need to do something with it you need to reassign something then you would have to use this method where you're accessing where you're getting the index but if you just want to let's say out put each item or you want to you know use each item without reassigning it into the array then this sort of format is great what it's going to do is it's basically going to loop through every single item in my array and put it into this variable for you to use so let me comment this part out actually let me let me just comment this whole thing out and just a quick tip if you want to comment out a whole block of code you can press a command back slash and that just takes care of that so when we run our code here so you can see this loop very simply it's just printing out the items of the array so this is a quick and easy way to loop through items in the array all right some other cool things I want to show you how to declare an empty array I think this is really important to know because right here we are initializing this variable to this oh right but what really is the datatype for this array if you were to explicitly write it well I'll tell you it is an array so there's square brackets and inside you put the data type of the array so string this array can only contain string objects all right forgot to mention that part that your items in the array will be the same data type if you wanted to declare an array that is empty to start you could do something like this let's say empty array [Applause] so you could just have an empty array like that but you have to declare the datatype because there is no datatype inside this empty array for Xcode to determine what data type that array should be that's why we have to explicitly specify that right here or if you don't do this you can do something like this let's do MTR a2 is equal to you could do that as well so this is basically creating a new array object right this is a type it's a string array and you're basically creating a new object of that string array type and it's not going to contain anything by default all right now let me show you some ways to work with arrays in terms of adding items and removing items so you can let's sort of add items first so you can to my array there's methods like append so you're gonna pend a new element or you can even insert so you can insert a new element at a particular index and it's not going to overwrite it it's just gonna push everything back so let's say I wanted to insert a frog at index zero then if I let's say I copy this down here and I print out the items again you're gonna see that it starts with frog this time and then it goes dog cat bird so it inserted frog at zero and pushed everything else back now another way you can add things you can go plus equals just like that and then you can add a number of items to the back of the array so I can do frog there and why don't we move this print statement down here and let's see what is in our array at this point so we have frog dog cat bird frog and bear oh and that was that's because I inserted frog at the beginning and then I appended frog and bear at the back so that's our resulting array all right so let me just write it here in case you download the playground it's another animal that I can use there's so many animals out there raccoon it's not like I saw a raccoon out there but it just popped into my mind all right remove items so my array you can remove a particular item at a specific index like that it's gonna remove that item and everything is going to shift to fill its its place we can remove all right we can remove first or remove last we could move the first number of items so there are a lot of options here like I said these collection types are meant to make your life easier to manage collections of data and that's why there are so many handy methods for you to use another thing that you might find yourself wanting to do is searching for a specific item in your array or maybe finding out if an item exists in your array or not search your a rate and the method to use for that is there are a couple of options there used to be one called index of so you can it returns the index of the item that you search for if it doesn't exist in your array it would return negative one otherwise it will return the actual index button now there are methods like first index of which returns the first index where the specified value appears because theoretically like we saw before frog existed at index zero and existed at index maybe six or something like that in our array and then alternatively there is also last index of so you're searching from the back towards the front and it's going to return the last index of that item what you're looking for so those are a couple of handy ways for you to do some searching within your erase what I've covered in this lesson is enough for you to get the main benefits out of using erase as we continue to build apps together we're going to learn new ways of using a race but for now this is more than enough hi and welcome to my Swift tutorial for beginners in this video we're going to go through another collection type called the dictionary now these are really common especially when you're working with data from a remote database or from a third party API alright stay tuned I'm looking at the Swift documentation here and they give a really good example about the dictionary collection type and before we go into the actual example let's take a look at the differences between dictionaries and race which we went over in the previous lesson and talked a little bit about what makes them different and when you would use one over the other so in the previous lesson when we talked about arrays I said that it's kind of essentially a list of your data with order 0 all the way down sequentially now order matters write that data at index 0 is different from the data at index 1 2 or 3 the dictionary on the other hand is unsorted there is no order now how do you put data into a dictionary well data is put in as key value pairs so each piece of data that you put into the dictionary you have to give it an associated key to retrieve that piece of data later on think of it as kind of like well a dictionary where you have maybe the word being the key right when you're flipping through a dictionary or you're looking for the word the value that you get from finding that word is the definition so you can kind of think of it like that or in this case the example that they give is that the value is the airport name whereas the key is the airport code now one very important thing that I need to stress is that the keys have to be unique right or else it's not gonna work if you have two different pieces of data with the same key how are you gonna distinguish between the two when you look them up now why don't we jump into the playground and let me show you an example of how to declare a dictionary and some of the ways that we can use it alright first let's declare a dictionary so I'm gonna say var Mayan dictionary equals and just like an array you start with two square brackets like that and then inside you specify the data type of the key followed by a colon and then the data type of the actual value that you're trying to store so in this case I'm gonna put string colon string which means that my keys are going to be strings and my values are also going to be strained and just like you saw in the previous lesson about how to declare an empty array you can do the same thing I'm gonna declare an empty dictionary just like this so essentially this is the type of the dictionary alright so let's go ahead and put some data into our dictionary so we're gonna type my dictionary and then we're gonna have two square brackets in an index you would put the index in here right well for the dictionary instead you put the key in here now our keys are strings right so I'm gonna go ahead and put a new string key in here and then assign it the value that is going to be associated with that key now the example that I want to use is cars and license plates because the license plates are unique as well so why don't we just make one up so let's say something like that and let's say that this is a red Ferrari and just like that I've put in some data into my dictionary with this associated key now how do we go ahead and retrieve that value well let's try and print that out first you go to my dictionary and then you put in the square brackets and you pass in your key so ours would be SJD 2 9 3 so let's go ahead and print that so you can see that it is a red Ferrari but notice that it's wrapped in here in an optional type the reason for that is because if you try and access let's say a key that doesn't exist let me just make something up let's just say 1 and there is no key in our dictionary with 1 you know as the key when you run it you actually get nil so that's why what you get from this is an optional type it could be a string or it could be nil all right so I'm going to write down some comments here assigning data into a dictionary this is declaring and Mt stroke stroke dictionary this would be retrieving a value [Applause] as often all straight so typically when you try to retrieve the value for this key you would assign it to something like that let's say my car is equal to this and then you would have to check using one of those methods we talked in the optionals lesson like checking it against nil using equal equals or using optional binding or anything like that okay so how about placing the value for a key so let's say we changed cars but we kept the same license plate well in order to change the data for that key you would just assign it something different so let's call it black Lambo all right so just like that we've replaced the value for that specific key now let's say that you've sold the car and you've kept the license plate so here's how you remove a value for a key equals nil simply by assigning it now like that you're essentially removing the data for that key and the last thing I want to show you is how to iterate or go through the items of the dictionary and remember there is no order but we can still loop through the items of an of a dictionary by using the for loop so it would be for something right for something I'm not I don't want to write it right now I just want to fill in the other part for something in my dictionary and then in here do stuff for each item of the dictionary now what is this something in here well since dictionaries work in key value pairs right so we basically use something called a tuple and a tuple you can think of it as like a collection of variables and what we're gonna put in here is let's say key and value so it's going to take each item out of the dictionary it's gonna put the key into this variable and it's gonna put the value into this variable all right so we can do something like this print key let's say I'll see what that does we should put another car in here just to make things a little more interesting let's just use okay let's try to print this now so we get our two keys but we only have one ah that's because we're we removed this car for this key why don't we go ahead and comment that out so we still have two cars in our dictionary and why don't we run it now so now you can see the two keys we can also print out the value instead you'll see our two cars here now we can use them separately we can insert the key say is a value could do that so that's how you iterate through a dictionary so that pretty much wraps up using a dictionary and you will find that it will come in handy alongside using a race when it comes to organizing your data so if you liked this video please hit the thumbs up button and please subscribe if you haven't already now click on over to the next lesson and we'll talk over there
Info
Channel: CodeWithChris
Views: 227,539
Rating: undefined out of 5
Keywords: learn swift, learn swift programming, learn swift 5, learn swift in one video, learn swift programming language, learn swift fast, swift tutorial, swift 5, swift programming, swift tutorial for beginners, learn swift 2019, learn swift with bob, learn swift ios, learn swift for beginners, ios, app development, mobile development, apps, developer, programming, tutorial, code, ios development, learn to code, swift language, learn swift from scratch, swift programming tutorial
Id: FcsY1YPBwzQ
Channel Id: undefined
Length: 188min 8sec (11288 seconds)
Published: Fri Jun 07 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.