Swift Tutorial - Full Course for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello welcome to learn Swift programming for beginners lesson 1 today we're gonna talk about variables you're gonna learn about what they are how to declare them in Swift code and furthermore how to use them alright so let's get started for the rest of the lessons in this series we're going to be working inside this app called Xcode Xcode is the tool that Apple has provided for people to build apps with and inside Xcode you're going to be able to create your user interfaces you're going to be able to write the code to express the logic in your app you're going to be able to test your app even so that's why this is where we're going to start in learning Swift we're gonna be writing the Swift code inside the app that you're actually going to use to build apps with in the future so this is where you're gonna get Xcode just go to your browser go to developer.apple.com / Xcode or you can launch the Mac App Store on your computer and search for Xcode there if you're on the webpage you can see that there's this big blue download button up top now ideally you want to make sure you're using the latest version of Xcode and right now as of this recording it's 8 and you can check your version if you go to Xcode you can see it here in the welcome screen and you can also go up here to Xcode about Xcode and you can see what the version is if you're a PC user and you're running Windows there may be some additional work you need to do before you can run Xcode or you might have to use an alternative solution to build iOS apps so check in the description below for PC solutions however if you are a PC user don't let that discourage you for me personally I lost about 2 to 3 years of learning iOS development simply because I didn't have a Mac and I didn't want to get a Mac but these days there are alternative solutions you don't actually have to buy a Mac computer although I eventually did and now I haven't looked back so anyways now that you have Xcode and after you've installed it it's a pretty large install it's pretty big program so I might take some time but after you have it installed and you launch it you're going to see this welcome screen you can see here that when you want to create an app for iPhone iPad Mac or whatever you're going to go to create a new Xcode project and that's gonna start a full-out project for you to build an app in but here we're gonna start a new playground because that's gonna allow us to type some code quickly it's gonna let us run that code and see the results and we're not committing to building in a project it's simply like a sandbox or a playground as its named now if you don't see this welcome screen what you can do is just go up to file new and hit playground right there and that's going to start a new playground for you as well or you can just hit this button get started with a playground so that's gonna launch this dialog for you and I'm simply going to leave the default name there platform should be iOS and I'm going to save this on my desktop okay so after your playground runs you'll see up here it's doing a whole bunch of stuff a launching simulator getting it ready and when it's done all that it's going to say ready you can already start typing in code so there you go it says ready but when it doesn't say ready and it's doing something then chances are whatever you're typing here is not going to show up on the right-hand side okay we're going to start with a quick tour of this playground window here so down on the left hand side I have a bunch of line numbers now if you don't have these and you want them they can be useful at times especially when I'm teaching and I need to refer to line numbers you can go to Xcode preferences and you can go to text editing and you can simply enable line numbers there now this area right here is where we're going to type our Swift code and it's already got a bunch of stuff for us right here which we're going to go through in a second on the right hand side you're going to see a quick preview of the results of what you typed there now a lot of people have trouble with getting output to show up on this right-hand side based on what they type here well one of the things that you can check is just in this status bar up here make sure that it says ready and as you're typing something let's say I change something like that you're going to see that it for a brief second there there was a little spinner because it's evaluating your code here if you wanted to show up just make sure it says ready to process your next command and you know you should see that output there alternatively there is a tray down here which you may not notice because it's hidden at first you can hit this button to show the debug area or there's also this little button here to hide the different panels okay but we don't need to see all of that but this debug panel may be useful when we start to output things here this is called a console area where we can use swift commands to output things this blue icon here is to execute the code in your playground so if you can't get things to show up on the right here try clicking this button to run your playground right now it's blue because you can see there's a little drop-down arrow there if you click and hold it you can see whether you want to switch it to automatically run and that's going to run the playground whenever you type something or you can set it to manually run and you can see now it's grayed out so if I type in some new code it's not actually going to change or display what I have on the right-hand side here unless I click the play button to run it so I would recommend to have it set to automatically run so now that you know in the main areas of the playground let's get into the meat of today's topic variables and in fact what we have here is a variable in Swift a variable hold some data now this data could be a value it could be a reference to an object or it can even point to a function which are things that will get into the future but for now we're going to say that variables hold theta now as you can see from this example line of code a variable has a couple of distinct parts let's break it down variables need to be declared before they can be used so this VAR keyword is used to declare a new variable following the VAR keyword you have the variable name in this case it's STR and really that's it you've declared your new variable so it's got the VAR keyword and it's gotten the variable name now taking a look at the whole line what we have on the right hand side there that's some data we did say that variables hold data right in that equal sign in between the variable name and the piece of data well that's an assignment operator so what we're doing in this line of code is we're declaring a variable called STR and then we're assigning that piece of data to that variable so now jumping back into the playground let's see the effect of that I can say something like print which is a keyword that is going to print something to that console area down below so if I say print and then in the parentheses I put STR you can see that it's printed that hello play out s ruff lying down there on the right hand side we can see a quick preview of that and notice that there's a /n here and that is basically just denoting that there's a newline associated with that print statement because the next time I print something it's going to be printed on the next line so you don't see that here because a newline is just a carriage return or whitespace you can't really see it but in here in this preview it's visualized as that /n which is just a newline so let's take a look at a couple of different pieces of data that we can store in two variables so I'm going to declare another variable here called a and I'm going to assign a number into it so just var one and I'm going to declare another one called B which I'm going to also assign one and I want to show you that you can perform operations between the variables or on the variables so for example I can say print a plus B and you can see here that the result in the console here is two now notice that what I'm using the variables in an equation or an operation like this I don't need to use the keyword var because that's only for declaring variables alright so this little part is declaring the variable but when you use them afterwards you just need to refer to them by name so let's try some other things print A - B I'm print a times B okay so variables hold data and you can perform operations on variables now you can change the data that the variable is holding so I can say something like a equals two now right in fact actually let's not do it down here let's do it here after we've assigned one into a let's say a equals two and as a result you can see all of these operations have changed because a is now two so a plus B is three a minus B is one and so on because a is now two now when you assign something into a a different piece of data it replaces what it was holding on to before so a is no longer one it is now two but notice how when we assign a new piece of data into a we don't have to write var again that would cause an error because we've already declared that variable up here in memory in the system has been allocated to it and so we don't need to read eclair it all we need to do is assign new data into a like that now if you're playing around in the playground yourself you may notice something like what if you try to assign something into STR like one well you're gonna get an error and that's because of something called data types which we're going to learn them out in the next lesson but for now just know that for STR because we've assigned some text into it up there if we want to reassign some data into it again it has to be text as well so that would be valid furthermore you can also assign a variable as another variable so I can say a equals B down here and in that case a would now equal one again well it was one to begin with so let's say I did that so if a was two and then I said equals B then now they would both be one now before we move on a quick note on naming variables here we have a variable STR and I've named some variables a and B so normally you want name variables like a and B because they're not descriptive of the data that they hold so if you're going to be using variables just like this in an operation wouldn't it be easier if you knew what a represented and won't be represented well you can declare your variables using any sorts of names that you would want but you can't put some special characters and you can't put spaces in your variable name however the common practice is to use a form of camelcase where the first letter is lowercase so let me show you what I mean so I can say var and if I want to describe my variable if it represents let's say the number of apples that I have I would say something like my number of apples like that and you can see that each new letter of each word is capitalized except the first one now you don't want to get too crazy with the length of the variable name as well and you don't want to go too short so short that it doesn't actually mean anything so there's no right or wrong answer or hard limits it's based on you know your own preference and it's more important if you're working in a team with other people that you agree on a certain coding style because you're both going to be working on the same code ok so one more thing I want to talk about our constants so they are like variables except that once you assign something to them you can't reassign data into them so that's really the only difference that and also how they're declared so with variables you use the keyword var but with constants you use the keyword let so I can say let C equals 10 and then down here if I try to reassign something into C like that Xcode is not gonna like that and it's gonna throw an error and it's gonna tell you with this red dot down here and if you click it it's gonna say cannot assign value to C because it's a left constant now it gives you this little bubble here what you can click and smartly it's gonna change let to var because it senses that you want to reassign data into it so you might ask why would I ever want to use a constant if it's more limited in its functionality right if I declare everything as variables then I have the all the flexibility I had one well there are a couple of reasons why you'd want to use constants when it makes sense for one thing it helps the computer work a little more efficiently because it knows exactly what that constant will be and that's not going to change but more importantly it's that for you as a coder you know that that constant isn't going to change because when you're building your app you're gonna have a lot of variables and when you have some sort of issue in your app and you don't know why it's happening and you're tracking down your code you're tracing it line by line and you're trying to see if maybe at some point you've accidentally assigned something to a variable and that's throwing off all your calculations or all over your logic it's going to be a nightmare to try to solve and untangle so if something you know it isn't gonna change you can assign it to a constant and then when you're looking through your code you can be sure that the issue doesn't lie with that constant because you know it can't change okay so that's it for this lesson on variables I hope you're practicing on your own computer with Xcode and check below this video for a link to the cheat sheet and the notes hello welcome to learn Swift for beginners lesson 2 in this lesson we're going to talk about data types did you know in the previous lesson that you are already working with different data types well let me point it out to you let me open up the playground that we were working with in the previous lesson do you remember how we were trying to reassign data into the variable STR and I was assigning something like a number into STR and I told you that you couldn't do that in fact Xcode tells you that you can just do that right here so if we take this little console area and we scroll the scroll bar all the way up to the top the error message actually tells you what's going on cannot assign value of type int to type string well what's an INT and what's a string well those are two examples of datatypes just as the name implies a data type is a classification or a type of data for example a string is a data type that described pieces of text and int short for integer is a data type for whole numbers negative or positive however there are many more data types than just these two other types of data that you'll commonly be working with are float for floating-point numbers or decimal numbers and then there's double for decimal numbers where the decimal portion may be very large and then there's boolean which represents true or false or in other words yes or no these are some of the more common data types that you'll be using and the reason why there are different types of data is because the system stores different types of data and differently and so when we go back to the playground and we take a look at this variable that we declared here STR and it stores a string the system has allocated this variable to store this piece of text or string in other words and when you try to assign an INT into that same variable it doesn't allow you to do that because strings and intz are stored differently now you might be wondering what differentiates a variable that stores a string like this STR variable versus a variable that stores a number or an int like this variable a well when you declare a variable you learned in the previous lesson that you use the keyword var and then the name of the variable well optionally you can also put beside the variable name colon followed by the data type and if you declare your variable this way you're basically telling the system that this variable can only store this type of data and if you omit that part and you just simply declare your variable with var and then the variable name then what it's gonna do is as soon as you assign a piece of data into that variable it's going to take a look at what type of data that is and assumes that that variable stores that data type so now going back into the playground here it's as if we declared this st our variable like this right and these ones are like this now for instance if I declared this STR variable like this then this line would be an error because I'm trying to assign a string into a variable that is of type int so it's not going to like that now let's change this back to a string for a second and go back to this line where there's an error now you understand why this line is in red because we can't assign an int into a string variable well there are ways to convert data from type to type in some cases it makes sense like 29 here this in can be represented as a piece of text simply like that right but conversely this hello playground line right here I can't convert that to an integer because it doesn't make sense that this message could be represented by a number so for example just as a little preview here if I wanted to convert this number or this integer into a string I would create any string and pass in the number like that now I'm not gonna go into detail about why this works or what this line is because then you're gonna have to learn about classes and initializers and stuff like that but for now in this lesson I want you to understand that there are different data types why there are different data types and how that comes into effect when you're declaring your variables and working with your variables and your data now before we end this lesson off let me just show you a couple of examples of the other data types we talked about so float could be something like that a double usually also looks like this and you're not going to have a really large decimal point unless it's like a result of a calculation that you're doing and let me show you a boolean which is represented as bull so you can set this to the keyword true or false which is going to come in handy for the next lesson that we're going to do on if statements oh and there is a mistake here because I'm read éclairs e did you see that in the previous lesson we talked about how you can tree declare a variable C we declared VAR c up here but i forgot that we had tried to declare a constant with the same name down here so this is going to have to be f i'll show you some other types of data conversions here so i can say let's print out let's change c which is a float into an INT and what's going to happen is that it just drops the decimal portion of that so if you did print let's convert d which is a double into an integer you can see here that it just chopped off the point 9 and you get 13 now there is a rounding function which we can try out right now like that and then inside the parentheses you can put d which is our double 13.9 and what you're going to get as soon as it finishes processing is 14 like that but notice that the result is also a decimal number see it has a point zero there so what you can do is wrap the result of that rounding inside a pair of brackets like this inside an INT and then you'll get 14 without the decimal okay so that does it for data types hello welcome to learn Swift for beginners lesson 3 in this lesson you're going to learn how to express some simple decision making in your Swift code using if statements all right let's get started so for this one we're going to start a brand new playground alright so we've done this before let's just call this one the if playground and I'm going to store this on my desktop ok so we're talking about if statements today and this is really exciting because it lets us finally start to make decisions through code and express some sort of logic so for example if I have let's declare a constant here so let a equals 10 for example and I wanted to print this statement only if a is less than let's say 11 which it is right here but mmm okay actually that is that is not right let's say 4 and this gives us a reason to use the if statement right ok so print only if a is less than 4 but a is 10 right so we shouldn't be outputting this so what we can use here is an if statement and what it allows us to do is only execute some code if a certain condition is true so in this case we want to print this only if a is less than 4 so we can write an if statement too check if that's true or not before we print that statement so let me show you what that syntax looks like and if you're not familiar with programming terms syntax is simply like the grammatical structure of the language so it's basically the key words to use and how we go about declaring an if statement or writing an if statement so it all starts with the if keyword following the if keyword we have the condition in which we want to check and following the condition we have a set of curly brackets now inside the curly brackets that's where we put the code that we want to run if that condition is true so that's your very basic if statement now going back to our playground let's write it out and print this only if a is less than four so we can do something like that if a and then we can use this operator less than four and remember we need to surround the piece of code that we want to execute if the condition is true using a pair of curly brackets like that so you can put the curly bracket on the same line or you can put it on a second line it doesn't matter but what you usually want to do is indent the code that is inside it it's just so it's easier to read I usually like to put this curly bracket in the same line like that okay so now you can see that in the console there's nothing printed and also to the right here it doesn't give you a preview because this condition is false a is not less than four because a is ten now what if we changed a to one and let the playground process okay now it prints this statement and it previews this statement see it's printed down here so that's your very basic if statement now there are other cool things that you can do with an if statement there is an else if Clause so for example using the else if clause you can check a sec condition if the first condition evaluates to false and the syntax for that looks like that so you have your if condition and then you have your curly brackets and then you use the key words else if and then you check another condition and you have another set of curly brackets so if you write it this way you're basically checking condition number one you know is that true if it's false now you're checking condition two and if that actually evaluates to true then you're running the code inside that else if block now keep in mind that it kind of goes from top down and if the first condition is actually true then it's gonna run that piece of code inside the first set of curly brackets and it's just gonna ignore your else if statement so let's take a look at that inside the playground so here I'm gonna put else if a is less than let's say eight then now I'm going to print only if a is less than eight so now I'm gonna change just not this I'm gonna change a back to ten here and you can see nothing gets printed because first it checks this condition if it's false which it is then it's gonna check this condition and it's also false so nothing gets printed now what if I changed a to seven now if I change the a to seven you can see that it prints the second statement because first it checks this condition that's false so now it checks this condition and that actually turned out to be true so it's going to run this line of code here however if a is 1 then it checks this first one and then it prints this one and then it totally ignores all of the other else if conditions now I said all of the other else if conditions right I say that because you can have as many else--if conditions as you want so you can say if a US is less than ten and then you can you can continue adding as many conditions as you want but keep in mind that it checks from top to bottom and as soon as it finds a condition that is true it's going to run that piece of code and ignore all of the other conditions now finally there is a clause that you can run if all of the conditions are true kind of like as a fail-safe or as a last resort and that is the else keyword so the way you write this is using the else keyword it's not else if it's just simply else and there's no condition attached because if all of the conditions above it are false then it's going to run the code inside of this else statement here so going back to the playground let me show you what that looks like else print nothing was true and now let me change a back to ten here so you can see that it prints nothing was true because it's checking the statement it's false this statement is false and sorry I mean conditions and this condition is also false because a is not less than ten a is actually ten so this would actually evaluate to false and finally it just gets to this else Clause and it's going to print what's in here okay so let me show you a couple of other things that you can do with L statements and let's change these print statements to something that is a lot more recognizable or easy to read let's do that branch one branch two and here oops branch three okay so first of all let me show you how to do less than or equal to now you see it prints branch three so that's how you do less than or equal to and likewise you can do greater than or equal to and you can see here it's still prints branch three now what if you wanted to check if it was exactly ten you wouldn't do that because remember this equal sign is an assignment operator so what you need to do to compare if a is equal to ten you use the double equal sign like that you can see here it prints branch three okay so why don't we introduce another constant up here let's say B and let's have that equal to four I want to show you that your conditions for your if statements and your different branches can get pretty complicated and you can involve multiple pieces of data in your condition so you can go if a is less than four if you want to check B as well and you want to say you know and B is less than four that's how you would do it you would use this double ampersand sign and now you're checking two conditions you're checking is a less than four end B less than four and only if both of those are true are you going to get this branch here so let's try that out so if I set B to 1 and a 2 1 then both of these conditions here are true so it's gonna print branch 1 however if I set B to 10 all right it's going to just see it hits this branch too now because a is 1 which is less than 8 and it didn't print branch 1 because this was false right even though a is 1 and this part is true we have to have this part to be true as well because were you saying is a less than 4 and B less than 4 in is ten right now however you can also do or so you can say is a less than four or be less than four and in this case either condition can be true and that would cause it to go into this branch so you can see now it is in branch one alright so let's say a is ten and B is 1 so a is not less than four but B is right because you're using this or statement you're saying is a less than 4 or B less than 4 and if that's true then we're coming into here now furthermore if you wanted to involve let's do a C you can combine you know multiple conditions like this you can put this into a pair of parenthesis like this and you can say you know and C is equal to 3 so you can see now that you're saying okay is a less than 4 or B is less than 4 and also is C equal to 3 then come into branch 1 now these brackets matter a lot because what you're doing is you're saying that this has to be true and this has to be true but for example if I just shift the brackets a little bit and I say something like this then that changes the meaning completely because now I'm saying is a less than 4 or is this part true right so where your brackets are matter a lot and it changes the meaning of what you're checking did you get that in this case I am checking is this true or is this true but the other way around I'm checking is this true and is this true all right so the brackets matter finally let me show you another operator that we have here so here we have we're checking is C equal to 3 well what if we want to ask is see anything but 3 or is C not equal to 3 if we only care about the case where C is not 3 we can say something like this not equals to 3 and this is going to say is C not equal to 3 so you can see here that C is 3 so that's why it it completely skips this branch and it ends up being a is equal to 10 and it prints branch 3 now you can use this not operator this exclamation mark here on other things as well so for example here I'm asking is a equal to 10 right and I am it's coming in here because a actually is 10 and so it's printing branch 3 but if I surround this like that let me put something else's in here is a equal to 10 and B equals to 1 right that is true so that's why I'm still getting branch 3 but if I put an exclamation mark here like that it basically flips it around so this evaluates to true right a is a 10 this evaluates to true both the this whole condition evaluates to true right 8 is a equal to 10 and B is equals to 1 and then so we get true but then we're adding this guy here it flips that true to a false so that's why this whole condition equates to false ok so that does it for if statements I hope you're trying this out on your own computer in the lay around because trust me it's pointless to try to memorize all of the keywords and the syntax for the swift it's much better if you you know only spend thirty minutes instead of trying to memorize things spend 30 minutes in the playground just punching in different numbers like that playing around with the different conditions and expressions and printing out a bunch of stuff in the console in 30 minutes you'll remember a lot more just by doing that then trying to memorize you know how to declare a variable or how to declare an if statement so you know if you can get a Mac get Xcode open in a playground and then type this code out for yourself and and play around with it it's going to do wonders so thanks again for watching and if you like the series so far please give the video a thumbs up please subscribe it really helps hello welcome to the learn Swift for beginners series lesson 4 in this lesson you're going to learn about switch statements and like the if statement it allows you to make decisions with your code alright so let's get started let's start by creating a new playground for this example and I'm gonna start labeling these after the lessons here and I should have done this sooner but I want to point out that Apple does have a swift programming language guide and in this guide it goes through all of the syntax and the structure and the different concepts of the Swift programming language it's what we're doing in these videos and more in fact so if you want something to read you can go ahead and visit this website here I'll have the link below the video but one thing to note is that it may be a little bit complicated for the absolute beginner who doesn't have programming background but give it a try and it's a great compliment to watch with this learn Swift series that you're watching in fact as we're going through the different concepts and these videos I'll point out in the guide where they are so for example we're looking at the switch statement today and that resides under control flow and you can see here what the basic syntax is for this which statement okay so let's jump back into our playground and we can do an example of a switch statement so in here I'm going to basically do the same example or similar example as the one in the guide and I'm going to introduce a new data type called character and it's basically like a string except that it's just a single character like that and with an if statement we can do something like this if some character is you know equals mm a for example okay like we have right here print is in a and this is going to be true and it's gonna print this out and then we're gonna have else if and we're going to maybe check another condition if we wanted to you know respond to different cases depending on what letter this variable is right but you can use a switch statement and it looks like this so we start with the switch keyword then you have the value which you're considering in our case that value is in the variable some character so that's what we would put in there and then you open up a pair of curly brackets inside these curly brackets you have different case labels so you would have case if you wanted to consider the case where the value is an A you would have case a and then you have colon and you would have something to do if it were that case perhaps this would be easier to visualize if we take a look at the playground so let's jump back to the playground here so let me say switch statement right on the value that we're considering so that's some character and you open up a pair of curly brackets like that and then you have your case labels so I have case you know if it's an A and if I want to do something for this case right then you have a colon and in here you would print it's a is an a like that and if there's another case right I would have case be for example and I would say is a B and lastly if none of those cases are true I would have a default case like that and I would say print mmm some fallback so in this switch statement this case was true right so it printed out this statement and it doesn't do the rest and you can have more lines of code in here than just the print statement in all of our examples you know I just wanted to show that it's coming into here this branch but you could execute more code in here now the case where you know character is a B then we would come into here and jump into here now if it's not none of those cases we would have default and it would print that and of course you can have a whole bunch of different case labels it just doesn't have to be the two that we have here and the benefit of using a switch statement is that rather than using an if statement and having all of these else if clauses reading this is much more clean and it's a lot easier to read as well so what if you wanted let's say two different cases to run the same piece of code or the same block of code so for example if I change this to say is B or you know a C is a B or C I could do something like this with this case label here I can do that comma and then I can put this other case there so this saves me from having to have another case C and then you know the same code I can put a comma here put the other case here and have either one of these cases use the same block of code so now you can see that it comes into this case here prints is a B or C instead of coming into default so why would you want to use a switch statement over an if statement well if there are a lot of different conditions that you want to check on a certain value rather than using an if statement with a whole ton of else ifs you can use this switch statement which is easier to read and easier to understand you're probably going to use the if statement more than the switch statement but it's still a handy tool to have in your arsenal so I highly recommend that you try this out in your playground so that's it for switch statements this is a short one I hope you enjoyed it please help this channel grow by subscribing and hitting that thumbs up button below the video hello welcome to learn Swift for beginners lesson 5 in today's lesson we're going to talk about loops when you're writing your app there's going to be many times you're gonna find yourself needing to repeat pieces of code for instance let's say you're showing five things in your app and you need to turn each of them red so a loop is going to allow you to just write that single line of code to turn something red and you can repeat it five times for each of those five objects and that's going to save you from having to write out that code five times so that's a very simplified example but trust me you're going to use them a lot so let's take a look at how to use them so there are three types of loops we're going to cover today we're gonna start with the for in loop as you can see in the Swift programming guide here so let's go ahead and start a new playground in our Xcode and I'm just going to call this the loop playground and save it on my desktop now a for----in loop allows you to repeat a piece of code a certain specified number of times if you have a list of data otherwise known as an array which you're going to learn about in an upcoming lesson you can also use a for in loop to go through each of those pieces of data in that array and execute some sort of code on it so this is perfect for the example we mentioned in the intro about having five objects or five items on the screen and you need to turn each of them red for example so let's start with learning how to use a four end loop to repeat a piece of code for a specified number of times and when you guys learn about arrays I'll show you how to use a foreign loop to go through each piece of data in that array so as you can see true to its name the key words to use here are four and in so you start with the keyword 4 and next you have a variable name now you don't have to declare this variable using the VAR keyword like you've learned in the previous lessons you can simply have a name for this variable because you're only going to refer to this variable within the for in loop this variable that you specify here is going to keep track of which iteration of the loop is currently running next up you have the keyword in and then you have the lower range followed by dot dot dot and then the upper range and that last part there after the in keyword is the range which your for loop is going to run in and it's inclusive of those numbers so for example if you have one dot dot dot 5 it's actually going to run 5 times and then after that you open a set of curly brackets and inside the set of curly brackets that's where you're going to put the code that you want to repeat for that number of times so let's jump back to the playground and let's do a quick demo on that for in loop so I have the for keyword here and for my variable I can specify something like index and then I would put in and let's use that same example 1 2 5 and then I open up a set of curly brackets and in here I'm simply going to print hello and we're going to see this in the console down here it is printed at 5 times now part of the reason why you specify a variable name here called index is because you want to use that that number or the variable inside your for loop here so for example I can do something like this or I can say print index and you're going to see that index changes from one two three four five depending on which iteration of the loop it is it keeps track of basically where we're at in this range right here as we're looping through it but again what we've specified here as a counter is only available inside this scope here in between these curly brackets I can't specify you know printing index out here it's not going to recognize it okay so we can't do that and furthermore if you don't need to use index inside your for loop you can very simply place an underscore there so this is perfect for the example that we had initially where we're just printing hello five times we don't really need a counter of any sort where we don't need to refer to index we don't care which iteration it's currently at one thing I want to mention which is confusing often for beginners is this idea of scope here for example if I wanted to sum up the numbers from one to five and I wanted to print out the result after the for loop let's say I declare a variable up here and I call it sum I equate it to zero and then I say something like sum plus equals and actually let's add this index variable back here and I go like this now you haven't seen this plus equals sign yet but this operator basically equates to something like this it takes some and it adds the index so this is equivalent to writing this is just kind of like a short form okay so first of all if I declare this variable called some inside my for loop inside these curly brackets well this variable is only available within that scope within these two curly brackets I can't go out here outside of the for loop after it's run five times and print out the result of some see you can see that it can't find this variable even though I've declared it in here okay so why don't we move this print statement into the for loop what would you expect to happen in this case well we get one two three four five again and why is it that this sum isn't increasing why isn't it continually adding index to it and you know why aren't I getting the sum of the numbers from one to five by the last iteration of the loop well what's happening is that in the first iteration of the loop we're declaring sum equals to zero and then we're adding index to sum which is one and then we're printing sum so that's why we get one down here in the second iteration of the loop what we're doing is we're declaring some again we're setting it to zero and we are adding this time the index is 2 and we're adding 2 to 0 right and then it's going to print 2 so that's why you can see the output 2 right there well right now you might point out to me hey Chris I thought you said that you can't read it clear the same variable you know in the first iteration the loop we're declaring var sum right and then in the second iteration of the loop weari declaring for some that's that's illegal that's not allowed in fact you might say that you know if I declare var string again up here it's gonna throw an error all right we can tree declare the same variable because we've declared this guy up here we can't read eclair it using the var again and I would say that's true except that in each iteration of the loop it's almost as if it doesn't remember what happened in the previous iteration there's no memory or recollection of the previous iteration so each iteration is kind of like a clean slate and it's going to execute this code right here so just to say that again you're right if you're saying that I can't read Eclair some right because if I try to do that right here Xcode would throw an error however inside of a loop in this scope right here each iteration of the loop is like a clean slate okay now if I wanted to actually find out the sum of the numbers from 1 to 5 what I would actually do is I would move this declaration up here outside of the loop and then what I would do this way I could move this print statement outside of the loop and what this for in loop will do is simply loop from 1 to 5 each time adding index to the sum and now I'm actually keeping track of the sum so you can see that after five iterations of the loop adding the numbers from 1 to 5 into sum which started out as 0 the result is 15 down here and that's from this print statement okay so I'm going to stop the lesson there while the syntax for the for in loop is actually pretty simple and and the concept of repeating a piece of code for a certain number of time is pretty simple I want to give you some breathing room to digest what we talked about in regards to the variable scope so I would recommend that you try declaring and creating this loop on your own computer try declaring the variables inside the loop and outside the loop and see where you can access them and use them and where you cannot it's really going to help and aid you in your learning hello welcome to learn Swift for beginners lesson 6 in this video I'd like to introduce you to two more types of loops and that is the while loop and the repeat a while loop in these two loops let's you execute some code until some condition is met so that's different from the foreign loop where it repeated a certain number of times okay let's do it for this lesson we're going to create a brand new playground and I'm just going to call this the loop to play around okay so let's cover the while loop first take a look at this slide and let's go through how to declare a while loop so the key word here is while followed by that you have some sort of condition and it's very similar to an if statement so the while loop is going to repeat that chunk of code as long as the condition is true but as soon as that condition becomes false it's not going to repeat the code anymore after your condition you have a set of curly brackets and inside of the curly brackets that's where you have the code that you want to repeat so let's do a quick example back in our playground so I'm just going to declare a variable here I'm going to call this let's say counter and I am going to set this counter to ten and then I would like to print hello I don't see use five instead so it doesn't print that many times and I would like to print hello as long as the counter is above zero let's say so I would say something like while counter is greater than zero I would I would do this print right here however this is going to keep repeating as you can see because counter is always five so inside my while loop I'm going to computer is dying okay as you can see it eventually overflows and crashes okay so what I'm doing here is I am decrementing counter by one for each iteration of the loop so as you saw when I didn't have this line of code it just kept printing hello many many times because this condition would always be would always be false there was nothing changing the counter variable from five to zero so I'm just going to warn you about that if you're gonna try this on your own computer you know if you have a slower computer and might it might take a lot longer for you to get out of that out of that loop so you can write this statement first and make sure you have a statement that is decrementing your counter so again this minus equals is the equivalent of writing something like this counter equals counter minus one so you're just taking whatever value counter is your minus thing one and you're setting that as a new value for counter as you can see here it's what you would expect right you get hello five times now let me point something out to you right here what if counter was let's say negative five you can see here that nothing gets printed out because this loop is going to see if this condition is false or true before executing the code right so it valuates the condition and then it decides whether or not it should run this and repeat it now the second type of loop the repeat while loop is very similar to the while loop except that it checks the condition after looping once so it checks the condition down here let's take a look at the syntax so you start with the keyword repeat and then you have a set of curly brackets and inside the set of curly brackets you place the code you want to loop or repeat and then after the ending curly bracket you have a while keyword and you then you have the condition so the syntax of this repeat while loop is very intuitive actually it's basically saying repeat this piece of code while this condition is true okay so let's go back to the playground and let's do an example here so I am going to use the same example ok let's print hello here and we're gonna have the same thing counter equals counter minus 1 and we're going to say repeat this chunk of code while counter is greater than 0 so as you can see it's pretty much the same loop or same condition rather write while counter is greater than 0 and that's the same thing I have up here for this while loop and let's just print something else here so we can differentiate it and you can see the repeat while loop actually prints it out once and then it checks the condition and it realizes oh I shouldn't repeat this chunk of code because this is false right whereas this while loop it checks the condition first and it realizes this condition is not true and it won't print at all so that's that's the main difference between the two types of loops both types of loops will repeat of chunk of code until a certain condition is false except that the while loop checks first and the repeat while loop checks the condition after repeating once hello welcome to learn Swift for beginners lesson 7 in this lesson you're going to learn what functions how to use them what they are and this is a critical part of the Swift programming language if you want to build apps with it so let's get started so here I've got a brand new Xcode playground where we're going to take a look at what functions are and how to use them how to define one how to call one if you don't know how to start a new playground just go back to lesson one of this learn Swift series okay let's start with what a function is at it's very core a function simply allows you to take a chunk of code give it a function name and then whenever you call that function name it's going to execute that chunk of code now that may seem simple but over the course of the next couple of videos you're going to see just how complex and powerful functions can be functions are really useful because it allows us to break down and group our code into smaller chunks and we can organize them so that each function or each chunk of code has a specific task and when you want to do that specific task then you just call that function so let's see how a function is defined in Swift code and then we'll jump into some examples in our playground so here we have the syntax for our basic definition of a function now it can get more complex than this because there are a lot more features of functions that we can use but we're going to explore those in the next couple of videos for this example here is your kind of basic definition of a function you start with the func keyword that's f UNC followed by the function name now this function name is what you're going to use to call the function now right after the function name you have two parentheses or two rounded brackets in this basic definition there is nothing in between these two brackets no spaces nothing in the next two videos you're going to see what those brackets are used for but for now those brackets are just there as part of the definition there's nothing in between them and then you're going to have a set of curly brackets and as you would expect in between the curly brackets you would put the code for the function so whatever you call the function name that code in between those curly brackets that code is going to be executed all right let's jump into the playground and do some examples I'm going to declare a function that is going to add two numbers together and it's going to print the result to the console so I'm going to start by using the funky word to declare a function and now I have to have a function name so I'm going to say add two numbers that's my function name and you'll notice that I'm using the same camel case as I do for declaring variables where I start with a lowercase letter of the first word and the following words uses a capital letter then I have my two rounded brackets like that followed by a set of curly brackets like that and sometimes when you type in this first curly braket or the opening bracket and then you press Enter Xcode will automatically add this ending curly bracket for you okay so in between the two curly brackets I am going to say let a equal one let B equals two and I am going to let's see equals a plus B okay and then finally we're going to print the result of C so you can see here that nothing actually happens because this function hasn't been called this code is sitting here if we had written this code instead of putting it into a function so let me just delete this for now like that and this is what we've been doing so far before we learned about functions we would just declare these constants here and then print C and you would see all of this stuff in the output now I'm just going to undo those two deletions so to wrap this code inside of a function now you can see nothing gets output until I actually call the function to execute this code right here so how do we call a function so in order to call a function you just have to write the function name followed by the two rounded brackets now because we don't have anything inside these two rounded broq that's all we have to do but as you're going to learn in a couple of videos later if we have something in between these brackets the calling the function would require a little more work but for this basic function we can invoke that function simply by writing its name so add two numbers as you can see here autocomplete even suggests so all I have to do is highlight that line press ENTER and what happens now we get three output into our console because by calling that function it just ran the code down here and I can call this again as many times as I'd like and anywhere I'd like one benefit is that if you need to execute a chunk of code several times this is a big savings rather than writing this code out multiple times I just put it inside a function give it a name and now I can invoke that piece of code whenever I call this function name like this so it helps you reuse code especially if that chunk of code is going to be used multiple times in your app you don't want to write out the same chunk of code multiple times in and around your app because it makes it really hard to debug for example if you've got an issue with this chunk of code and imagine if you had it repeated several times in your app in order to fix it you'd have to fix it in every single one of those places but if I have this chunk of code inside this function I would only have to troubleshoot and debug this piece of code once here and as soon as I change this let's say I change this a to a two and let's say that fixed my code and you can see here wherever I call add two numbers the code is updated so I only need to update and change the code in one place whereas if I wrote this chunk of code out in multiple places in my app I would have to change it in all of those places another benefit I mentioned is that it lets you group this chunk of code that performs a specific task into a function that describes what that chunk of code does so it helps you organize your code so there is one more thing I want to mention about functions and that is about scope so same thing we learned about inside of loops in terms of defining variables applies here as well so let me give you an example of what I'm saying so let's say I get rid of those two function calls and we simply have this function here we have these three constants C is obviously four right and inside this function I'm printing C so outside of my function let's say I want to print C well that is actually going to throw an error that doesn't work why because the constants and variables that you declare inside a function can only be used in the function in between these two curly brackets and likewise if I declared another function really quickly so inside this function I also cannot access the constants that I declared here so if I declared constant like that D equals 1 I can't say you know let e equals C minus D or something like that inside this function it's not going to recognize what C is right here so let's get rid of this first okay so there you can see the error it doesn't know what C is because C is defined inside add two numbers and so it only recognizes C within this scope a B and C in fact so inside here inside this function I'm free to declare a again because it only applies within these brackets like that so I can have a minus D and let's end off by printing e okay so the main takeaways for this lesson right here you've learned about what functions are and why they're beneficial you've learned how to define a simple function you've learned how to call that function so you can execute the code inside of that function and furthermore you learned about the scope inside of a function and just to remind you about that it's that whatever you declare inside of the curly brackets of a function is only recognized and can be used inside of those curly brackets in the next video we're going to build upon what we learn here in this lesson and you're going to learn how to make functions even more powerful so thanks for watching if you liked the video please give it a thumbs up it helps this video get seen by more people and subscribe for more hello welcome to learn Swift for beginners lesson eight in the previous lesson you learned about functions how to declare them and how to call them in this lesson you're going to learn how to use them in a even more powerful way by having your functions accept data and also return data to you when you call them alright let's see how that's done so here I have a fresh playground if you forget how to open up a new playground just go back to lesson 1 of this series and you can see how now there's one thing I want to mention before we move on that I forgot to mention in the previous video and that is that sometimes I may accidentally say method and when I say method I actually mean function now I noticed that a lot of other Swift teachers also do this and the reason for this is because for many Swift educators like myself Swift isn't our first programming language and in many of the programming languages out there there is some concept of a function and sometimes they're called functions sometimes they're called methods and sometimes even other things so a lot of the educators out there when they're teaching sometimes they're going to slip up and they're gonna say method instead so I just want to put it out there if you hear me say method just know that sometimes I use function and Method interchangeably okay so we're going to start by just read eclair enough unction to previous lesson and I want to read eclair it just for extra practice for you guys so I think it was something like add two numbers like this and it was let a equals one let be equals one and let's see equals a plus B and then we're going to print C just like that now in the previous lesson I mentioned that functions are great for kind of organizing your little bits of code into pieces of code that perform one task so in this case this function would add the two numbers together and then it would print out that sum in the console but what if I wanted the function to just add the two numbers but don't print it out I just want the result so in fact functions have something called a return value and it's exactly how it sounds when you execute the function it returns a value to you so let's take a look at what the syntax is for specifying that a function returns a value so everything remains the same as our basic function definition but after the two rounded brackets you have an arrow that arrow is just comprised of a - and a greater than sign and followed by that you have the data type of the value that this function should return so now that you specified that this function returns value you have to use the return keyword inside of that function to actually return a value of that same data type that you specified so now let's go back to our playground and see how this applies to the function that we have there so let's say that for this function I don't want to print out the sum instead I wanted to return the sum to me I would then erase this print statement first of all after the rounded brackets I would put - greater than sign and then I would put int specifying that this function should return an int data type now Xcode immediately throws an error here because it notices that I don't have the return keyword I'm not returning an integer value like I said I would so what I would have to do actually to fix this is used the return keyword and I'm going to return C because that's the sum of a and B so now when I call add two numbers like that it actually returns see now let me show you something here so when I type that autocomplete it shows you the return value right there it tells me that add two numbers actually returns an integer like that so what I would do essentially is I would probably declare a constant and let's call it sum and I would say equals add two numbers what's happening here is that I'm calling this function add two numbers and this function is returning C as in the sum of one plus one and I'm assigning that value into this constant called sum so now if I print sum like that I would get two so this constant sum it stores the returned value from my function here so one more thing I can do up here instead of declaring this constant C equals a plus B and then returning C I could actually get rid of this constant and I could just return a plus B like that and that would actually take a and B add them together and then return it so that's return values for functions and this is really powerful because now you can write a function that does something and returns the result to you so your function is kind of like a little worker or a piece of code that does a specific task and then returns you back the result now there's another cool thing that you can do with functions and that's called parameters C this function by itself add two numbers it's always just going to add one and one together and return to to me but what if I wanted this piece of code to be reusable for any type of numbers I want to specify which two numbers I want to add together so essentially what it is is when I declare this function I can specify in between these two rounded brackets see I mentioned in the previous video that we would use this in between these two rounded brackets we can specify that this function needs some input parameters in order to execute so let's say that I'm going to declare this function and say that when you call this function you need to give me two numbers as inputs now when I call the function here I would have to specify two numbers in between these rounded brackets okay so before we actually do it let's go take a look at what the syntax looks like for declaring these input parameters so this syntax right here shows you what the function definition would look like for a single parameter now we're going to get to multiple parameters but this is an example of a single parameter function declaration so in between the two rounded brackets you have an argument label okay and I'll explain to you in a second what that is and then you have a parameter name followed by a colon and then followed by the data type of the parameter you're accepting now let's talk about the parameter name : data type part first so obviously the colon data type part of that specifies what sort of parameter you're going to be passing into the function and the parameter name is going to be the name of that parameter you use within the function so if I wanted to take that input and I wanted to add it to something and I wanted to reference that value that was passed in I would use the parameter name okay inside the function now the argument label for that parameter is what is going to be shown when you call that function I know it's a little bit confusing right now but let's jump into an example so it makes more sense all right so back to the playground here let's implement one parameter inside our add two numbers function here so I'm not going to use any descriptive names right now because I want to show you how the argument label and the parameter name plays out so I'm going to say add two numbers are label is let's just say argh and then the parameter I'm just going to say para okay and then : int so this function now accepts a parameter that is type of int and then Xcode detects that now this function call is incorrect because we have no function that doesn't accept the parameters so one cool thing you can do is just erase that and go add two numbers you can see that autocomplete now recognizes that we have a parameter so let's double click that and you can see here is the argument label let's pass it in a number here let's pass in let's pass in two like that so by specifying arg there as the argument label for the parameter when I call the function I'm going to have this label here if I wanted to use this number that I passed in remember you have to use the parameter name that's four inside the function so I would reference the value that's passed in using the parameter name like that so essentially what I would get here is because I'm passing in two and I'm referencing I'm setting a as two right that's our parameter that just got passed in it would be two plus one so that's what is stored into some and when I'm printing some that's what I expect to get three okay that is helpful but it's not complete we want to be able to pass in both numbers so that we can specify which two numbers to add together let's take a look at the syntax for multiple parameters so the syntax for multiple parameters is very easy in the parameter list that is that stuff between the rounded brackets you would just put a comma after the first parameter and then essentially repeat the same thing for the second parameter you'd have an argument label followed by space followed by a parameter name colon and then the data type now you want to use different or labels and different parameter names obviously so that you'd be able to tell it apart now let's jump back to the playground and add our second parameter so what I would do in between these rounded brackets in this parameter list is I would just put comma and then I would put my second argument label my second parameter name followed by the data type which is another int now again Xcode is going to throw this error here let's use autocomplete again add two numbers you can see here it's been updated to accept two arguments so argument just Arg and Arg - so let's pass in two and two now we have to modify our code a bit right now I'm still getting three and that's because inside this function code I'm not using the parameter two yet we can change that like that so now a gets set to parameter I mean para and B get set to para two and then I'm returning a plus B so now I actually get four in here so one thing we can do with this function is actually we don't need to declare a equals para and B equals para 2 that doesn't really do anything so we can get rid of these two constants here and we can simply return para plus para 2 like that straight off the bat now our function is pretty simple so at this point you might be wondering why is it so confusing that I'm using argument labels here in the function call and then we're using parameter names inside the function code well what you can do is you can actually not specify argument labels like that and just have the parameter names and what it'll do is it's going to use the parameter name both as the argument label and the parameter name so now this is wrong you can see xcode here has an error let's use autocomplete to see what the new function looks like the new function call and you can see here that now the argument labels are the their names so we can also change our parameter names at this point you probably don't want to use pair around para to for your own function so we can say you know number one number two if we have these us our parameter names then you know this changes as well number one number two and then our function call would also change like that okay now you might be wondering why why use argument labels at all like what are they for well with using argument labels you can make your function calls a little more like natural English so let me show you an example you can do something like this add two numbers so there's my first argument label and number two like that so let's take a look at what our new function call would look like so when I'm calling a function add two numbers using two and two all right you can see how that reads more like natural English and it makes intuitive sense what the parameters are going to be used for meanwhile inside our our function here if my parameter names were using right or and it doesn't make much sense right you know if I didn't use if I used these as the parameter names like that these would be terrible parameter names because if my function is really long this doesn't tell me anything this doesn't tell me anything doesn't mean anything to me while this function call still makes a lot of sense when you call it in terms of natural English but in in the actual code in here and add two numbers you know adding using it and n doesn't really make sense so if you use the combination of argument labels and parameter names that make sense you have this function call that is like natural English and makes sense and you also have meaningful parameter names that you can use inside of your function okay so I want to show you one more thing if you don't want to use these argument labels at all what you can do is replace your argument labels with an underscore like that or you can replace one or you can replace both so let me show you what that looks like so I'm gonna replace both the argument labels with just underscore let's take a look at what that looks like now so you can see now that I just pass in two and two like that no parameter names no labels no arguments no nothing it's just you pass in the input parameters like this and you these are your parameter names so that's what you're going to be using inside of your function okay so just to recap in this lesson you learned about return values you learned about the return keyword and you learn about input parameters and how to specify them what argument labels are what parameter names are and also how to omit argument labels all together I hope you enjoyed this lesson if you did please give the video a thumbs up and please subscribe for more hello welcome to learn Swift for beginners lesson 9 in this video you're going to be introduced to classes which is an absolutely critical part of the Swift programming language if you're going to be using it to build apps I'll tell you all about it let's get started so I'm gonna start off with a hypothetical example so let's say you have something like a blog post which you would like to represent we might have something like a variable here for blog title all right blog title can be hello playground I don't know what kind of article that would be but we would have another variable for the blog body and this is the you know text of the article or the blog post and then we might have something like blog author which in this case let's just put my name here so you can see here this is the data for one blog post now let's say I had two blog posts what what would I do in this case I might have another set of variables down here and of course I can't have the same variable names so let's just append two to these these variable names and let's say this is I don't know this article is good by playground okay now this is what I have for two blog articles now what if I had ten what if I had a hundred how many variables would I have then it it'd be a ton right it would be a mess there needs to be a better way to represent a blog post to kind of group these variables together and there is in fact that's what a class is you know how you learned about the different data types back in lesson two you learned about the string data type you learned about the int data type float double boolean all of those are data types to represent different types of data right well with classes you can define your own custom data type so what we're going to do here is we're going to create our custom data type called blog post for example you can do that with classes let's take a look at the syntax for declaring a new class so first of all you have the class keyword next you have the name of the class and this is going to be the name of your datatype then you follow by two curly brackets and inside those two curly brackets is your class definition let's take a look at this back in our playground so for example up here let's create and define our class so first I would use the class keyword and then I would create a name of the datatype or the name of the class in this case let's put blog post and notice that this time I'm starting off with a capital letter in fact all of the data types in Swift start off with the capital letter so we should follow the same convention I always start off your class names with the capital letter and that's different from what we've been doing with variables and constants and functions okay then I have these two curly brackets like that what do I put inside of my blog post class well why don't we put this stuff right here I'm just going to cut it and I'm going to paste it inside here and then I'm gonna delete this right here and I am going to delete this text inside these variables inside my class and leave them empty and I'm going to explain why in a second okay so just like that we've defined a class called blog post and this class has three properties now a property is just a variable declaration like this but inside a class it's called a property and you're gonna see why in a second why it makes more sense and because this blog title blog body blog author is inside of blog post it's kind of redundant to name them like this so I'm just going to name them title body and author like that okay so this this represents our blog right here now that you've defined what a blog post is let's create an actual blog post because remember this class definition right here this is just a definition of a data type you're defining what a blog post data type is right so that's not an actual blog post just like how this is a string that's not the definition of a string that's an actual string so in order to create an actual blog post we're going to type in the class name followed by two rounded brackets like that and just like that this is a new instance of the blog post type and it's called an object or blog post object so when you define a new class using the class keyword that's what's known as a class definition or just class but when you create actual instances of that class those are called objects you can think of your class definition as a template or a blueprint and you use that template to create actual tangible blog post objects so let's jump back to the playground here this is a very important concept to understand we've defined a class called blog post here it's got these three properties or you can think of them as attributes of a blog post and then down here like this we've created a new blog post object now this blog post object has a title it has a body and has an author but all of it all of them are empty right now so what we're going to do is we're going to assign this blog post object into a constant let's call it my post like that so what we've done here is we've created a new blog post objects we've assigned it to my post and now why don't we try setting the title of this blog post and the body and the author what we would do is say my post right that's referring to this new object and then we press dot and that lets us access those properties which we've defined in the class definition I set the title to I don't know hello playground I think that's what we had before let's set the author of this one and let's set the body to hello okay just hello now if I print my post dot author I would get my name now let me show you something else we can create a second instance of blog post or a second blog post object and let's call this my second post and we're going to set this to a new blog post object like that and we're gonna say my second post title equals goodbye playground and we can set the author to someone else let's say John Travolta I don't know why that suddenly popped into my head and let's just do hello again now this is a second my post object this is different from my post these are completely two different blog post objects both of them contain these three properties which we can set because that's what we've defined here in this class now another very cool thing about classes is that you can put functions in them all right you can see how all of the lessons so far are coming together let's create a new property for this first let's say a number of comments equals 0 this is the number of comments in the blog post and we're going to define a new function in this blog post class we're gonna say add comment okay and we're not going to worry about the comment text just yet let's just define this so notice that in my function definition I have these two curly brackets again inside here this is gonna be my function code so inside this function I am just going to increase the number of comments by one this is all stuff that you should have learned already in the previous lessons now okay so now every single blog post object is going to have this function now how do we access it we simply go my post dot you can see now in the autocomplete that there is this function called add comment and it doesn't have any return value it doesn't return anything so the return type is void right there let's call this function okay see what happens so add comment you can't visibly see what happens but let's print my post dot number of comments you can see that it's one okay now let's print my second post dot number of comments what would you expect this to print out it prints out zero why because we haven't called the add comment function on my second post we just did that with the first post each of these blog post objects maintains its own properties changing the properties of one object does not affect the other even though they're cut from the same cloth right there both types of blog posts there are two independent entities and they maintain their properties separately now there's a lot more to classes but fundamentally I want you to understand what they are so I'm not going to make this video any longer than it needs to be I just wanted to introduce classes to you I hope you can see why classes are a fundamental building block to organize your information so thanks for watching please give this video a thumbs up if it helped you and please subscribe for more hello welcome to learn Swift for beginners lesson 10 in this video you're going to learn about inherit otherwise known as sub classing which allows us to build upon previous classes which we've already defined and it saves us a lot of time and effort and work so that we don't have to keep defining classes that do similar things okay so let's get started and see how this works let me start by doing a small recap of what you've learned in this series so far so you learn about variables and constants to store and keep track of data you also learned about some control flow and conditional statements so that you can express logic and make decisions with your code and then you learn about functions where you can define blocks of code that perform specific tasks as a way of organizing your code into more manageable chunks and then you learn about classes which is a further way where you can organize related code and related functions together as well as related variables in the form of properties and then today you're going to learn about inheritance aka sub-classing as a way to further organize your code okay so let's take a look at inheritance in a playground so I'm going to launch Xcode here I'm going to get started with a brand new playground and let's call this in here tunes playground okay let's just save it on my desktop there and get rid of this line of code so let's say that the app we're building is kind of like a car simulator or something like that and we need to define a class that represents a car so we're going to start by creating a car class just like that and some of the things that it may have is for example it needs to keep track of a top speed right because different cars may have different ranges for the top speed I'm just going to initialize that to 200 so there may be a whole ton of other attributes or properties to do with cars but for demo purposes I only need one so I'm not going to go further than defining top speed there and I wanted to find a function so car by definition is a vehicle that can be driven right so I'm going to create a function called drive just like that it doesn't accept any parameters and inside this function it's going to perform all the code that we need to drive a car but you know for this demo I'm just going to print driving at and then I'm going to put in top speed like that so this this value in this top speed property gets substituted in there and then it prints out driving at whatever this value is 200 so what I call the drive function it's going to print this statement out into the console okay so we've defined our class here that represents a car and in the previous lessons you've learned about how to create a new object right from the car class so why don't we declare a constant called my ride and we're going to create a new car object and assign it into the constant my ride just like that we've created a new car object now let me try accessing top speed where you press dot and then you can access the property there as you can see it's running the playground okay you can see 200 there and let's try calling the function my ride dot drive that and you can see it says driving at 100 okay so now let's say that in this driving simulator app I also have something called a super car or maybe a future car so it's the car of the future for example and it can fly so it's the flying car that it will probably come in the future so we can define another class to represent that and we can call it future car right and again this future car because it is a car still it's gonna have a top speed and let's say this top speed is 250 like that and it's also got a function called drive and because you can still drive this car and again it's just going to print you know driving at top speed and also this car can fly so let me define another function that represents you know flying the car so flying I'm just gonna call it flying like that so here we've defined our car class we have to find a future car right here if I want to create another let's call it my new ride this is a constant and this time I'm going to create a new future car object like that and then my new ride you can see has fly now right and has Drive and it has top speed now let me ask you this question see we you can see the similarities between car and future car right they both have the properties of a basic car like a top speed and they both have this drive function which is very very similar in fact it's actually identical so this is pretty redundant right there's a lot of redundancy between these two class definitions so this is where inheritance or subclassing comes into play and it's very helpful so what inheritance allows us to do is say that one class inherits from another class and essentially what that means is that if future car inherits from car it's going to inherit its properties and functions so you don't need to redefine them inside future car so let me show you what I mean here let's in future car let's delete this top speed property and let's delete this drive function and what I'm going to do instead is I'm going to make future car inherit from car and the way you do that is after the class and then class name you put : like that and then you put the class that it inherits from so in this case I would but car so in this sort of relationship we have car at the top and we have future car at the bottom inheriting all of the properties and the functions from the car class in this case future car would be called a subclass of car and car would be called the superclass of future car and some people might call it the parent class so car is the superclass or the parent class or maybe simply the parent of future car let's go back to our playground and take a look at what this means for our code here so you can see that my ride is still a car object and it still has top speed and it still has Drive but take a look at my new ride right it's a future car object and remember inside future car we've just defined a fly we haven't defined anything else in here but if I type in my new ride and I press dot here and let autocomplete do its thing you can see that future car actually has a drive function and actually has a top speed so you know if I do top speed you can see it's 200 and if I do drive you can see that now future car or my new ride rather is also driving at 200 and furthermore actually my new ride can also fly okay so there's flying now there's actually a problem here because right now my car and my future car they're both driving at the same speed but remember the future cars are faster right or initially I wrote the top speed was 250 so in this case what we can do is to do something called overriding and that allows you to take a function or a property from the parent class or the superclass and redefine it to essentially that's where the word override comes from so you're overriding the parents version of that function and you're providing your own implementation or your own version of it let me just do it here so you can see what it means so we use the override keyword like that and then we have to declare drive exactly as it is in the parent class so what we're doing is we're going to say print driving at and we're going to instead say top speed plus 50 because this guy goes faster so now you can see that when I call this guy what I call future car drive it doesn't use the parent classes drive function it uses its own overridden definition of what drive is and so that this is the code that it's running here and you can see it's driving at 250 okay so that's an example of overriding to provide your own custom functionality now inside this overridden method there is a way that we can access still the parent functionality and you can do that by using the keyword super so let me show you what I mean inside this over it in Drive function I can actually access the parent class the definition all the functions and properties in there if I type in super dot and then I can access drive so when I do this super refers to the parent class or the super class and this drive function is actually calling this guy up here all right so in this case it doesn't make sense you can see in the console when I type in future card drive it you know it calls the original definition of drive and then it prints this you know its own definition of drive so you know in this example it doesn't really make sense but sometimes when you're building your apps what you want to do is add functionality and not override the functionality if that makes sense so you don't want to replace what's in the parent class you just want to add to it and so you can do that if you you know you can call the original definition and then you can add your own code before or after that to provide additional functionality so in this case maybe I'll just change the statement here and rockets boosting at you know 50 or something like that so let's see so now you can see that this is my original car right when I call drive it says driving at 200 and then my future car is driving at 200 and it's doing something extra and so that's that's how this overridden function works okay so this is a simplified example of how subclassing works but it's essentially how it works and it's very predominant in the Swift programming language as I'm going to show you in the next lesson as you can see inheritance allows you to save a lot of work by taking what's already there and then improving it or providing you know alternate definitions so you don't have to redefine everything all over again but you can build upon the classes that you already have okay thanks for watching please help me continue to create more videos for you by giving this video a thumbs up and subscribing to the channel hello welcome to lesson 11 of the learn Swift for beginners series in this lesson I want to introduce to you UIKit it's an apple framework that contains many 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 like I mentioned in the intro for this video the uikit framework is essentially a library of classes that Apple gives us to build apps with when you think about it there are a lot of common elements to any sort of app for example apps may have views they may have buttons you know all apps are going to have things that you need to present to the user apps are going to need to handle user interaction from the person using the app and so on and so forth so to build that functionality out every single time you're going to build an app is extremely tedious and not to mention complex and complicated so Apple has provided UI kit for us to use and it contains a ton of pre-built classes for us to handle all of these common things so here I'm looking at the UI kit reference guide which contains a list of all of the UI kit classes that are available for us to use I'll link to it in the description below the video but if you want to look for it yourself just go into google and type in Apple space UI kit don't just type in UI kit because the first few results for that query isn't the Apple UI kit so just type in Apple space UI kit to find the correct one in the first result it was also essential to learn about inheritance before I told you about UI kit because many of these classes inherit from each other they build off of each other so they don't redefined things and this reference guide used to be kind of organized in a hierarchy so you could see which classes inherited from other classes but since they've changed it and they've made it kind of a listing so you don't get that but I did a google search and I found an image that I'm sure this is not the complete UI kit because this image was from 2012 I think yeah you can see here in the URL it's from 2012 but it does give you an idea of how the classes are organized so you can see at the very top of this tree if you can imagine this left side being kind of at the top of the tree and this right side being the bottom of it if you take for an instance this uibutton class which represents a button that the user can tap on the screen UI button inherits from UI control which inherits from uiviewcontroller or granddaddy and what this nsobject class does is it provides that basic functionality that allows you to create an object from a class definition so that's something we went through in part one of the classes lesson so this NS object class and it gives you that functionality and if we take a look at what was the next one down the chain so the UI responder class so this UI responder class inherits from nsobject means that it contains that foundation that's going to be needed by you know all of these UI elements or user interface elements okay so the next one down is a UI view so UI view inherits from UI responder which inherits from nsobject so UI view gets all of that functionality and on top of that the UI view class provides functionality for displaying something onto a view so a UI view is something that you can show to the user so it contains all of that functionality and code and then next in that hierarchy down to the UI button we have UI control now you like control contains all of that functionality before it following this line here and on top of that contains basic code and functionality for a user element control so stuff that is specific for displaying on to a view handling user in action and events and responding so then we have a specific type of UI control and that is the UI button which is pretty self-explanatory it looks and behaves like a button with certain button events so that's just one example of you know the path you can see that there's a whole ton of classes and there's even more now so whenever you go and you know before you go and do something with your app chances are you can probably leverage something from UI kit to build off of rather than building something from scratch so in this video I just wanted to give you guys an introduction to UI kit because we're going to be using a lot of classes from here and every time I do I will try and remember to reference this guide or at least link to it so you can take a look at these classes it's very useful and handy to have at your fingertips because you can click into these classes and then you can find out for this UI button class what sorts of functions it has and properties it has that you can use and leverage and how you can perform specific things with the button or with that class and furthermore I might do another video series where we go over specifically different UI elements because I think that would be useful for beginners to understand how to use for example like a date picker or a text field or a slider or switch or something like that so that might be a separate series aren't just UI elements please give this video a thumbs up and subscribe to my channel to help the channel grow hello welcome to learn Swift for beginners lesson 12 in this video we're going to talk about initializer functions for classes these guys exist to make sure that when you create a new object from your class that that object is ready to be used plus you can customize these initializer functions to set up the object any way you want when you create a new instance of the class let's get started and see what that means [Music] so what I've got here is a playground and I wrote down a basic class here called person and this person class has got two properties right now it's got a name property which I've initialized to an empty string and also it's got an H property which I've set to zero and that is an integer now you learned about classes in a couple of lessons back and you learned about how we create objects from classes right and in order to create a new person object I would say something like var let's just use the variable a equals person like that and we open up and close brackets beside the class name like that and here I've got a brand new person object and if I go a non name you can see that it's an empty string and if I go a dot age you can see that it's zero so what's actually happening when you create a new person object here and you write these brackets don't these two brackets look like you're calling a function but actually what's happening is you're calling the initializer function of the person class but you might ask we don't have one defined in here what initializer function are you talking about let me write it out by default it exists and if you don't customize it you don't really have to touch it but that initialization function looks like this it just uses the keyword in it and it has these two brackets and then in here in between this just like a function you can define code in here this set up your object so what's happening when you create a new person object with this line of code here is you're actually calling this init function of the person class and inside here you can actually write code to customize things so for example I can say name equals Chris and H equals I believe I'm 33 I think I've lost track so what's gonna happen here when I create a brand new person object is it's going to call this a knit function and it's gonna set these two properties to these two values here so as you can see now name is Chris and age is 33 when I create a brand new person object now remember how I said that you can actually customize the anit function to set up the object the way you want it to be set up and we can do that simply by adding some parameters into this init function just like we would for any function that we set up so for example I can say I can say n is a string and a is an in so now I have to pass in these two values so let me just erase this part here and I'm going to create a new person object and now you can see that the autocomplete shows me this so for name I pass in Chris and for the int I'll pass in 33 but instead of sending this stuff to the hard-coded values now I can set up to what is being passed in here so that's N and that's a alright when I'm creating a new person object here I'm passing in these values that go in through this init function and then it sets the properties to those values which I pass in now remember if I don't want these parameter labels all I need to do is go like that and you we learn this through the functions lesson so you can review that if you forget why this is these are the argument labels by putting underscore there we're basically saying we don't need the argument labels now while we're on this topic of specifying these parameters here oftentimes and sometimes I catch myself doing this too is that when we're passing in these parameters the name and age and you're intending to set it to these properties here there's a tendency to name these parameters exactly like the property names because after all you name these property names to be descriptive right of what they represent so in the parameters you might be tempted also to name them the same thing well what happens is you get into this situation where you're trying to set this parameter into this property name but they're both named the same thing so it's a little bit ambiguous so that's where you can use this keyword called self and what how you would use it is you would say self dot name equals name so self refers to the object that is being created so you're saying to set the name property of the object to this name parameter so that's how you distinguish between if the property name and the parameter name is the same so I would do the same thing here like that so then this age refers to that guy and self dot age refers to the actual property there now another thing I want to point out is that I can no longer call person like that because there's no init method like that what I can do is I can actually have multiple initializer methods so if I do this let's let's say this is VAR b equals this person object well this b dot name is empty and b dot H is 0 right because these guys haven't been set after all I'm calling this initializer function here that doesn't set anything whereas this guy this initializer function actually sets the name and age to whatever we pass in now there's one very important thing we haven't talked about yet regarding init functions I mentioned in the intro to this video that the inant functions are there to make sure that the object is properly initialized and all of its values are set making the object ready to be used so in this case right here for the person class I've declared two properties and I've already preset them or initialize them to these values here so really the net function has nothing to do even if I did nothing as is in this case right here the object would be ready to use because these properties have values in the next lesson I'll show you how you can sometimes if you need to declare these properties without setting or initializing them to values so it would be something like this you one write it out like this but just as an example you wouldn't set it to anything so there would be no values in here in that case when you create a new person object the anit function would be responsible for making sure that these guys do have a value because if not all of these properties are initialized to values then the object is not considered to be ready to be used so the anit function is there to make sure that the values are set and like I said so far you haven't learned about how to declare these properties right here without sending them the values I've always have set them to something but in the next lesson you'll learn how to do that and then we'll dive a little deeper into initializer functions and talk about how there are two types called designated and convenience initializers and so on and so forth okay so thanks for watching remember to give the video a thumbs up and subscribe to the channel if you haven't already hello welcome to lesson 13 of the learn Swift for beginners series in this video you're going to learn about optionals and it's probably one of the most confusing things for beginners if you've ever looked at Swift code and you've noticed exclamation marks or question marks in the code then you've come across optionals so let's get started and find out what it's all about so right here I have a playground and I have declared a class blog post in fact if you've seen episode 9 the first lesson on classes then this is going to look familiar because this is the example that we used for lesson 9 and when I first talked to you about classes now we declared a couple of properties up here for our blog post class and these properties they represent certain things about what a blog post might have so for example the title the body the author number of comments and you can actually safely ignore this function so I'm just going to remove it because we're going to focus on this stuff up here you'll notice that each time I declare a property right here I immediately initialize it to a value so title body author are all initialized to an empty string right when they're declared and comments is set to zero right right when it's declared now this is all fine and dandy but what if you actually want some of these properties to be empty for example what if I want to tell if the blog post has an author or it doesn't have any author you might argue that well I can just check if author is equal to an empty string and if it's equal to an empty string then maybe there's no author well what if the author isn't actually a string what if it's actually you know we have another class here and we call it person and let's say that there's a name and we'll initialize the empty string but you know okay so in this case person is assigned to author so you know blog post has an has an author because it has this person object so how do we distinguish there being no author for a blog post well you have to be able to declare an author property and leave it empty because some blog posts may not have an author so the way to do this is if you remember from way way back then maybe lesson lesson 2 on data types I think you can actually specify for your variables the specific data type that it can store if you don't specify it basically the data type is inferred from what you assign into it okay so for example if I wanted the title to be able to be empty I would have to declare the type I'd get rid of this equals empty string because we don't want to sign in anything to it right we wanted to clear this property but leave it empty I would do it like that I would you know did : specify the specific type and then I would put question mark and that is an optional right there so when I declare this title is empty and this part basically tells us that the data type of title is string and this question mark attached to the string data type tells us that it could be nil which means nothing or empty it could be nil or it could actually contain a string so contrast this with the body property here this when it is declared is assigned this MD string so it's always going to have a value right whether it's empty string or maybe in the future we assign some text into it it's gonna have some text but you know this title property could be empty in fact it is empty right now as we declare it so going back to this example with the author potentially some blog posts may not have an author so we can't just you know initialize the author property to a person object because that would mean all blog posts at least have a person attached to the author right we want to make this property able to be empty all right so the way we do that again is we specify the specific data type put the question mark there next to the data type and we get rid of that part because we don't actually want to assign anything to it okay so in this way we have a blog post class which has an optional title property has a body which is initialized to an empty string so it at least always has a value and it may or may not have a person you know it could have nobody assigned as the author or can actually have a person object assigned as the author and number of comments will always have a value and starting at zero so you're going to want to pay attention now because I'm going to tell you how you should think of these optional properties that we have here and this is sort of metaphor or a visual that you can think of that I was taught when I was learning this stuff and that is to think of the title property this optional string it could optionally contain a value or not think of it like a box it's labeled string but you can't see what's inside the box you don't know if there's actually a string object inside or it could just be an empty box it could be an empty gift box if someone if you've been really bad and someone gives you an empty gift for Christmas that's never happened to me but if it has to you let me know in the comment section below but anyways you can think of an optional property like a box that may contain the actual object or it may not so how can you find out if there's actually the string object inside or not well you have to unwrap that box right you have to unwrap that gift in order to look inside and see and get at the the actual object and that's exactly what we have to do in code now with our optional properties so let me let me create a new blog post object here let me say post equals blog post like that and what we're going to do here is we're going to say hey print out post dot the body plus I don't know plus hello something like that okay so it basically just prints out hello because body is empty but let's just assign it to something like that so then we have something like hey hello right that totally makes sense because body we've initialized it to hey right when we create the blog post object it's already set to hey and then we concatenate hello to it and so when we print post body plus hello you know you're accessing that property and in your pending hello anyways that makes sense so we can no longer do that with something like the title right because that's an optional it's it's wrapped up in a gift box and you don't know if it's empty inside or if there's actually a string object inside so you can't blindly use it you have to unwrap that gift box and and check if there's a value or not and then use it so now before we use title we have to check if there's actually a string object or if there's actually a value inside that optional and the way we do that is we do something called optional binding okay so it's kind of like an if statement so you say if but then you use the word let and if you remember using the keyword lettuce declaring a constant right in fact that's exactly what this is you're declaring a constant here if let actual title equals title and then you open up these curly brackets so what you're doing here is you're testing sorry not title I meant host dot title because this is the optional property here what you're doing here is you're saying that you're testing you're unwrapping this this title property this optional and you're saying if there is a value in there then assign it to this constant called actual title and then inside here you can use actual title as the value but if there is nothing inside this optional and if you unwrap it and it's empty it's nil then don't execute this code inside so that's why it has an if statement here you're basically testing to see if there's a value inside this optional if there is you assign it to this constant and then you use this constant inside here if there isn't then it's just going to skip over this whole if statement so in here we can safely now we can say you know print actual title plus you know solute so there is no value in title so it actually skips all this but let let's say for instance we say here post title equals yo like that so now you can see when it does this optional binding and it unwraps this title because we have assigned something into it here it finds that hey I unwrapped the optional there is a value I'm gonna assign it to actual title so inside this if statement we can use actual title and do this but if I didn't have this line here let's comment this out you can see that it it completely skips this and it doesn't crash or do anything like that because we're safely you know checking if there's a value inside the optional first and then we're using it now there's always different ways of doing things so in the Swift programming language there's actually a way to UM be a cowboy and skip all this if you don't want to check it and you just want to use the value you know you know there's something inside what you can do is you can use you know you're gonna not check it you're just going to use it you can movie that the post thought title and you put this exclamation mark and this is called force unwrapping so what you're telling Xcode is you're saying that hey you know I know there's a value in here I don't need to check it I just want to unwrap it right away using this exclamation mark and I use whatever is inside of there right in this case it's yo so here we're you know we're accessing post title it's an optional property we don't care we're gonna force unwrap that and we're gonna take out that value and use it you know and so if you know there is a value inside you can do that but it gets a little dangerous because for example if there happens to not be a value in there and you're forcing wrapping it and you're trying to you know use the value well there's an error because and this is the error you get fatal error unexpectedly right because when you use this exclamation mark you're expecting that there is a value unexpectedly found nil when unwrapping and optional value right that is exactly what I was telling you you're forcing wrapping the title and you're trying to use it but it was actually nil so you actually get a crash and in your career of building apps you probably will see this error unexpectedly found nil so now you know why so the safer way to go would be actually to use optional bindings so I'm gonna press commands that now command Z for the Americans I'm gonna undo undo all right do something like that and this is optional binding so another way where you can test before using is just whoops it's just with good old-fashioned if statement and testing if it's nil so you can say something like testing for nil you can say if post title is not equal nil then print post title and because you have tested it that it's not nil in this if statement you can go ahead and force unwrap that and use it all right so that works you can safely use force unwrapping because in this if statement you've just tested that it's not nil okay now the reverse if you want to check that it is nil is post title equals equals nil it's not equals nil a lot of beginners make this mistake and they use one equal sign but one equal sign is for assignment remember that so if we're going to test for nil you're gonna use two equal signs like that and this is like optional contains no value okay optional contains value and in here for optional binding optional contains the value so as with all of the other things we're learning with Swift we can go deeper there's additional things to learn about optionals like optional chaining and other ways of using optionals but this is your introduction I wanted to to tell you about what the question mark means and what the exclamation mark force unwrapping and how to check an optional before using it I wanted to introduce you to these and high-level concepts and practically speaking you'll be using them most of the time like this and then in the future we'll touch upon the more complex things about optionals also you might be wondering why why and when you would ever use optionals but let me tell you you definitely will use it when you're building apps and when we do build our apps together you'll know what they are and you'll know how to declare options and how to unwrap them and how to check if they're no because you've watched this lesson okay so thanks for watching and please subscribe and thumbs up and share the video with other people you know who want to learn Swift as well hello welcome to lesson 14 of the learn Swift for beginners series in this video you're going to learn about properties which is something that we have been using already together since the class's lesson but we haven't formally introduced them yet so this video is for that in addition to that I'm going to show you some other cool things you can do with properties that you can't do with variables okay so let's get started so here I have a playground which defines two classes blog post and person and you might recognize this from previous lessons and in both of these classes we've defined some variables here well properties are nothing more than variables that are associated with a class like this so for example in this blog post class I have a title property body author and number of comments and if I create a brand new blog post object from this class let's say let my post equals new blog post like that and then in order to access this title property I would use the dot notation I would say my post dot title and I'm going to assign something to this property and let's just call it title of post like that and in order to retrieve that value from that property I would just use dot notation again and this would return the value inside that property so you can see that property is just like a variable where it stores a value and you can retrieve it but I don't know if I mentioned this before and that is that properties are independent between objects so remember we have to find this blog post class right here and from this class we can create many blog post objects for instance here I've created a blog post object and I've assigned it to my post now let me create a second blog post object I'm gonna call this my post too and I'm going to create a brand new blog post object from there so I have assigned title of post to the title property of this guy right here alright that doesn't affect my new blog post object so I can assign my post to thought title equals another title that and if I display this title you can see that it shows another title so the properties are really variables that are attached to the blogpost objects that I create and although each blog post object has a title property the values that they store are independent of one another okay so the second thing I wanted to point out with properties is that when you're working inside your class so let's say we're working on this blog post class and we create some functions here let's say add comment you know we're gonna create a function like that and we're gonna create another function maybe called share share article ok these don't really have to do anything I'm just I just need to create two functions for the sake of creating two functions to demonstrate this purpose okay so just disregard what what I'm calling them because they're not really going to do that function okay so what I wanted to point out is that these properties that you define inside the class they can be accessed inside any of the functions inside that class so inside add comment you know I might be performing some code to add a comment and I would be able to access let's say you know I can print title or something like that right that would access this guy well actually that's an optional so using what we learned let me just force unwrap it but my point is is that I can access these properties here you know or I can print let's say body for example you know and here likewise I can also print body all right within all of the functions inside this class I can access any of these properties up here and I can set them to from within any of these functions however if you declare a variable inside of a function that is what's called a local variable and the existence of that variable is limited to the scope of that function so what that means in plain English is if I declare a variable here let's say var my comment equals you know some comment like that I would not be able to access this variable inside this function here so if I try to you know print my comment you're gonna see it throw an error here saying that my comment was never used oh wait that's regarding this guy right here so this is just an optimization Xcode this yellow little triangle means that it's a warning it's not really an error so it's fine Xcode is just warning you that you declared this my comment variable and you assigned it something but you never used it so consider consider changing its name to an underscore which which is an optimization but we are going to use it so Xcode is just proactive because every time you're typing code it just scans your code and it tries to tell you about these optimizations that you can do okay so that's kind of a side note back to the main point I was trying to make and that is if you look at this error here on use of unresolved identifiers my comment that means that Xcode doesn't know what you're referring to when you try to print my comment here so even though we declared it here and we assigned it inside this function this variable because you declared it inside here is the scope of this variable or its existence is limited to whatever is inside these two curly brackets you know it's limited to the code inside this function now if I wanted it to be accessible everywhere you know I would create a property and I would use that instead so that's probably something you're gonna get used to as you're doing more coding is the scope of where you declare things so this is called the local variable because we're declaring it inside a function and these properties that we declare up here to whole values are accessible inside the whole class so what that means is that let me just delete these two functions for now so what that means is that if you have a function that lets say calculates a result or performs some sort of calculation like for example add up comment total or comment counts or something like that and the point of this function is to maybe sum up the number of comments that this blog post has and then at the end of the whatever you know you're performing calculations here um do some calculations and come up with as a result arrive at a result now what do you do with that result right you can either and you learn this in the functions lesson is that you can specify a return value so this this specifies that when you call add up common counts it's going to return a number for you so now you can say you know return whatever the result is whatever variable that's stored in right you can return it to the caller another thing that you can do to make it accessible later on because remember any variables that you declare inside here are local variables and they live and die inside this function here so if I didn't do the return value route and I arrived at some sort of calculated result and I wanted to save it for use for later on I would probably assign it to a property so I can say number of comments equals whatever result that I arrived at and by doing this when I call this function it's gonna do some calculations calculate the result the total number of comments right and it's going to assign it into this property and now I can use the number of comments in other functions or later on if I left it as a local variable it would again when this function finishes that would be lost okay so that's the difference between the lifetime or the scope of property versus local variables and now for the third thing that I want to show you in this lesson is something called computed properties and it's one of those things that makes properties a little more special than just plain old variables here so let me let me get rid of these two here so that we can I start fresh and we're back to where we started in this lesson you can do what's called a computed property and what that is is it just returns and what that is is it lets you do some calculation and return a result when you call it property so let me demonstrate here so let's say that we have let author equals person all right so there is our author and let's set the author's name to Chris King which is my name and now let's create a blog post my post equals blog post okay and now let's assign the author property of the post right let's assign author into it now author right here is this person right this person object that I created and finally let's set the title to let's say learn Swift for beginners okay so what do we have here we have an author object which has the name set to Christian we have a blog post object with the author set to this person object that I created and I also set the title to learn Swift for now what I wanted to show you is I'm gonna create a computed property up here I'm just going to add a comment so that it's just to make it stand out a little bit so I can save our full title is a string and I'm going to open up a set of curly brackets right right after it and what I'm going to say is check if title and author on not nil check that title and author or not no because title is an optional all right an author is also an optional and you learned about these in the previous lesson so you know what they mean they could return nil which is nothing right when you unwrap it so I'm going to use an if statement just to check so if title is not equal to nil and and that's the double ampersand which represents an end condition so if title is not nil and author is also not nil both of these conditions have to be true then I'm going to run this code inside then return title and remember because title is an optional string right that means I have to unwrap it to get the value inside and I'm going to use the exclamation mark to force unwrap it that means I'm going to tell Xcode I'm just going to unwrap that optional and use whatever is inside whether it's a value or it's an or whether it's nil and I know for a fact that it's not nil because I just checked it up here all right so I can safely and confidently do this so I'm going to say by and then Plus and I'm going to do the same thing with author I'm just going to force and wrap it and use it okay so let's see what it's saying here cannot be applied to string and person that's right okay so author is a person right so I can't I can't append a person object to the string what I meant to do actually is I meant to unwrap the author right to get the person object and then call its name property so that's what I actually wanted to do okay so right here Xcode is complaining that missing returned in a function expected to return a string so this computed property here when it gets called full title it's supposed to return a string and if title is not nil and author is not nil it is going to return a string but what if one of these things are nil either or in that case I'm just gonna use the else branch here I'm just gonna return let's say let's do another check else if title is not nil oops not equals nil then return just the title oops force and wrap that finally if the title is nil then I don't know well we can do other than return an empty string or let's say no title let's do that okay so this is awesome now this is a computed property and I hope you can see that from this demonstration what that means it's a property where basically you can perform some code you can do some calculation you can combine a bunch of things and return a result return something so if I say down here if I say my host dot full title what do you think it's going to display let me print it out because it's kind of truncated over here let me use the print so it prints down in the console it's learn Swift for beginners by Christian and I didn't have to set that right because this is a computed property this full title property is calculated by grabbing the title and appending by and then appending the author name and if we didn't have an author so let me just let me just get rid of this line here for setting the author if we didn't have an author it would just print out the title and if I get rid of the title and it doesn't have a title then it's gonna print no title and that's all of this logic here in my computed property okay so that's computer properties there's also additional things which we won't cover in this lesson we'll probably do another video on properties and that is getters and setters and property observers but this is a really great start to taking a look at properties so thanks for watching please like the video and please subscribe hello welcome to lesson 15 of the learn Swift for beginners series in this video we're going to revisit initializers and I'm going to tell you about designated initializers and convenience initializers okay well let's get started [Music] so right here I'm starting off again with the blog post class and the person class and of these properties here in the blog post class I'm actually going to uninitialized some of these properties so I can demonstrate for you what we need to do in the initializer because I mentioned before that one of the jobs of the initializer is to make sure that all of these properties are initialized and ready to go so even if it is an optional that is considered okay when you're declaring your properties inside your class there are basically three different ways of doing it so number one is this one where you declare the property and you initialize it to some sort of value right away so that's this body property right here and this number of comments property is equal to zero the next thing you can do is you can declare a property and set it to optional so you're specifying that it could be nil or it could contain a value but either way you have to unwrap the value and you have to check if it's nil before using it now the third way is probably the most dangerous way and that is using the force unwrap operator so let me show you what that means if I get rid of that question mark and I put an exclamation mark there and let's also do it beside author so what you're saying here is you're saying that title basically is an optional it could be nil or it could contain a value but you're going to leave it unwrapped so when I access the title property down here and I say post title Xcode is not going to have that sort of safe checking or warning us that it could be nil it's not going to provide any of those safety mechanisms and it's just going to let us use it as is so we can assign nil into title as you can see here it's nil and we can use it like a normal property right we don't have to check if it's nil or not or rather it is up to us whether we want to do it or not but however if you know the difference the flipside being that we make this an optional now there are some safety mechanisms in place if I just try to use this as this Xcode is going to warn us that hey you know this is an optional you have to check that it's not nil or you have to unwrap it first before you can use it so I might have to say if let you know actual title equals and this is using optional binding so basically we're checking if there's a value inside the optional first you know if something could potentially be nil it's probably safer to use an optional value so that it forces the programmer to actually check things before using it now if you set your properties like that then it could still be nil or it could contain a value but you sort of remove that safety checking that optionals provide so those are three different ways that you can set up your properties what you cannot do however is you can't just do something like that where you declare a property you don't set it to anything you don't specify that it's an optional or you don't specify that it's unwrapped and you just leave it like that in that case Xcode is going to assume that the initializer is going to set those two some values so let's declare our initializer here like you've learned in the past and inside here you can see that Xcode is still showing errors but if I actually initialize these things inside the initializer let's say author is equal to person like that then Xcode is going to stop complaining because remember when we create a new blog post like this it's actually calling the initializer so even though these properties right here title and author they're not set to anything they're not optionals they're not unwrapped this initializer is going to be called for sure when we create a new blog post object and inside here those properties get set to some value they get initialized and so at the end of the day this blog post object is going to be ready to be used now this initializer right here this is what is called the designated initializer and what that means is that this initializer function is guaranteed to fulfill those obligations of making sure that all of the properties are initialized before use in contrast we can have something that's called a convenience initializer and what that is is you use the convenience keyword followed by your initializer method signature so I might have something like this where inside this initializer I only want to provide a custom title well you might ask if I call this convenience initializer how is author going to get initialized right so what happens is inside the convenience initializer I call the designated initializer using the self keyword like this so now and inside here let's set title equals custom title so now when I declare a new block post object and let's say I use my convenience initializer like this and I pass in a custom title like this it's calling this convenience initializer but this convenience initializer is also calling the designated one which makes sure that at the end of the day you know the uninitialized properties will be initialized and then after calling that designated initializer then we set title to custom title so whether I call this designated initializer or the convenience initializer the title and the author properties will be guaranteed to be initialized and so the role of the convenience initializer is simply for convenience so that's the difference between a designated initializer versus a convenience initializer hello welcome to learn Swift for beginners lesson 16 today you're going to learn about how to manage a collection of data in what's called an array if you're working with many pieces of data it would be hard to manage them with simply constants and variables so let's take a look at how arrays can make our life easier alright let's get started now arrays are one of three collection types that are available in the Swift programming language for us to use and manage our data in this language guide you can see a diagram of this array on the far left side we're going to come back to this diagram in a second but first the definition so you can think of an array as a collection of data that is ordered by indexes now if that doesn't tell you too much let's jump right into a swift playground and I'll show you exactly how beneficial they are and also how to declare them and how to use them so first I'm going to delete this default variable here and we're going to create a couple of variables ourselves so let's say var a equals dog VAR b equals can't or C equals bird and now let's say I wanted to concatenate or add the word my in front of each of those values there so that I would have my dog my cat and my bird so I would have to do something like this I would have to go a equals my space plus 8 and this would result in a being my dog because we're adding the word my with space to a and a is dog and then we're reassigning that result into a again thereby overriding what was there before so now a is actually my dog I would have to repeat this for cat and I'd have to repeat this with bird I can't even use what we learned in the previous lessons in regards to loops to make my life easier I'd have to write this three times for each of the variables so here's the perfect chance to use an array to organize this collection of data so in order to create an array with the data already in it we're going to open up two angle brackets or square brackets if you'd prefer and inside these two square brackets we put each piece of data separated by a comma so we have dog we have cat and we have bird so just like that we have an array with three pieces of data and if you remember what I said in the definition that arrays are a collection of data organized by indexes what do I mean by that well you can see that there are three pieces of data here so there's three distinct spots you can think of it the leftmost spot here the beginning is index 0 or spot 0 if you'd prefer to think of it like that the next one is index 1 and the last one is index 2 so arrays start at 0 and because there are 3 items here the indexes go from 0 1 to 2 and now if I quickly bring up that language guide again you can see in this diagram that in this array there are 5 items and so the index is 4 6 eggs is 0 index from milk is 1 and so on until it reaches 4 even though there are 5 items because it's zero-based ok so let's go back down here so this is great that we haven't know right here but we need some way to reference that array so actually what we do is we can create a variable let's call it D and we assign this array or this collection of data into the variable D so now if I wanted to access dog for example I would write D and then I would write square brackets like that and in between the square brackets I would put an integer representing the index of the item that I want so let's say I want dog I would put 0 so you can see here I would get dog right and so we can print that out and that would print dog down here now if I change the index to one then I would get cat instead now let's do an example where we have something like this just to duplicate that I would say let's say a equals my plus D 0 like that I can do B equals my that's my cat and finally I would get my bird but then I mentioned that there was a better way to do it if we leverage what we learned in the previous lesson on loops well we can let's take a look at using for loops and simplifying our work here so remember for loops we'll loop a piece of code for a specified number of times and you can see here that I'm working with index 0 and X 1 and X 2 so this becomes really easy I can say for remember the next the next piece of the for loop is a counter so you know it's my variable to hold the current index and then you write in and then you write your range so I can write 0 0 sorry I mean 0 2 and this is going to loop from 0 to 2 so I think you can kind of see where I'm getting at what I'm gonna do is print my plus D and inside here where I put the index usually I'm gonna put counter and you can see here it took the playground a little second but that's exactly what I expect it to do here so in the first iteration of this for loop counter is 0 right that's the starting range so 0 gets passed in here and I would get this printed out this is dog D at index 0 right it's dog in the next iteration of the loop counter is 1 and so I'm actually accessing index one of my array d so that's why I get cat and then finally a loops again and counter as to and I would access this bird index here I want to show you another way to use your for loop with an array and that's simply to say for item in D so what this is going to do is it's going to loop through all of the items in the array D and in each iteration of the loop it's going to take that item or that piece of data and it's going to assign it to item so I can simply go like this so you can see that it gets printed out again right in the first iteration item is dog in the second iteration it's cat and the third it's bird so this is pretty simple way to write it and you can see that it saves a lot of work from doing it kind of one by one like this and one by one like this arrays in conjunction with loops really powerful stuff now with a race there's other cool things you can do let me just make some space here maybe I should delete this stuff you can actually declare an empty array so it's an array that would contain no data at first and the way you do that is just like storing things into a variable or a constant arrays can only store data of a certain data type that you specify so since it's an empty array how you would do it is you open up two square brackets you put the data type inside the two square brackets and that data type represents the type of the data that the array is going to store so I'm just gonna put string here and then you end off with two round brackets like that and just like that now e refers to in a that is empty right now doesn't contain any data with the intention of storing string type data in this array now if you're going to create an empty array like this you better be able to add data to that array right so what makes arrays really useful is that you can add and remove data from that collection so I can add or remove from this collection right here I can add or remove from this collection here let me just show you how to do that there are a couple of different ways I can do something like this D plus equals to angle brackets like that again and let's say I wanted to add mouse and now my D array would contain four items as you can see here dog cat bird and mouse in fact I can even add two pieces of data at once comma and then here I could put owl for example so it would add mouse and owl to that array so now my array has five items from zero to four right starts at zero one two three four make sure that you don't forget that plus sign right here because if you do that then essentially you're creating a brand new array with these two items and you're assigning it to D and you've just lost this data here so plus equal is for adding items now seeing this plus equals you might be tempted to use minus equals to remove items like this but that actually doesn't work unfortunately you can't remove items from the array like that what you have to do is the array actually has functions that you can call on it to remove items so you would say D and then you would press dot on your keyboard or the period key and out pops a list of functions that you can call on this array and using the append function is going to do exactly like this plus equal is it's going to add items into that array but let's look at the remove functions so you have remove all which is going to remove all the items in a ray but you can use this one here remove at and you can specify the index of the item you want to remove so if I put 0 like that that's going to remove dog from my array so now it's only gonna contain cat bird mouse and owl now what if I don't want to completely remove dog but I just wanted to change that element right there at index 0 so let me get rid of this removed line you saw that you can access items in the array by doing that right putting in the index there well you can actually change the item you can change what is assigned at that index by typing d square brackets put in the index you want to change and using the equal sign to assign something new into that spot so here let's say turtle and that is going to now change your array if I print D oops 0 i'm going to get turtle instead of dog because i just changed it up here the last thing i want to point out is that arrays also you can check how many items are in there if you look at the count and that's going to return the number of items in your array that is sometimes useful when you want to use a for loop with a range and you don't know how many items are in the array you can use this array dot count and get this number here but just keep in mind that although D has 5 items right here the index of the last item is actually only 4 because the first item is 0 it goes from 0 1 2 3 4 right even though there are 5 items so just keep that in mind if you're going to use this array dot count in conjunction with a for loop or something like that okay so that's where we're going to end with arrays as you can see when you type array dot there are a lot of different functions with arrays that you can do what I've covered here in this lesson is enough for you to use a raise and leverage some of the main benefits of a raise as we go on and we're building apps together you're going to be learning new ways to use a raise but for now these are the main things you need to know about a raise in order to start using them if you like this video please give this video a thumbs up please subscribe for more hello welcome to lesson 17 of the learn Swift for beginners series in this video we're going to go through another collection type called the dictionary in the previous lesson we went through the array you can see here on the left hand side and with an array we had a collection of items where the order mattered so you can see in this example here in the Swift programming language guide 6 eggs is in spot number 0 whereas bananas is in index 4 all right well a dictionary on this right hand side here is a collection type where order does not matter so in arrays we retrieve the item by this index here and with a dictionary because order doesn't matter we retrieve these values using a key so each value has an associated key when you put it into the dictionary and you need to pass it that same key and it's going to return for you the value now which collection type you use to organize your data is going to depend on obviously what sort of data you're storing it does order matter if it does then the easy answer is to use an array if it doesn't then maybe consider using a dictionary so this is a good example airports have these airport codes right so each Airport has an Associated key and that's a good point the keys should actually be unique for each value that you put in another great example if one to use a dictionary and this is the example that I'm going to use in this video is license plates so for example each license plate is tied to a car and each license plate is unique so the key can the license plate and the value can be maybe a description of the car or something like that let's jump into Xcode in this new playground that I have here and let me show you how to declare a new dictionary and how to work with it so why don't we declare a variable here and let's call it cardi B to represent card database and let's looks like my playground has crashed okay and what we're going to do here is to declare a new dictionary so we use the keyword dictionary and followed by that we have these angle brackets we're inside we specify the data type of the key followed by the data type of the value so for example let's pull up that example again in here in this dictionary the key would be a string and the value would also be a string and so in between these two angle brackets we will just put string comma string and in order to create a new dictionary object we would just end off with those two brackets and like that we have an empty dictionary which stores key value pairs and a key value pair is just a fancy name for one of these pairs of data you know a key and a value this dictionary stores key value pairs where the key is a string and the value is the string as well now there is an easier way to write this out without having to write so much let me show you that second way var car DV let's just say DB 2 is equal to use the square brackets and then you specify the data type of the key followed by colon and then the data type of the value and again we have these two brackets here to create a new instance of that dictionary or a new dictionary object and that's equivalent these two are the same thing doesn't this look very similar to declaring a brand new array don't get confused so for example declaring any string array would look like this would be my empty array that is expecting to contain string objects and this is an empty dictionary that is expecting to contain key value pairs where the key is string and value of string as well okay so we're going to stick with this sort of declaration here so I'm just going to go ahead delete this array example that was just for demonstration and delete that so now we just have cardi B is an empty dictionary now how do I assigned something into the car database dictionary well I would do cardi B and then I would use these two square brackets here and I would pass in a key or I would specify a key rather and this key would be a license plate right so you know this is going to be different depending where you are in the world but let's just say it's like that and then you assign the value into the dictionary for that key so this would be let's say a blue Ferrari now this value blue Ferrari is tied to this key GST 238 how do I retrieve the value well it's very simple I just give it the key so if someone were to look up this license plate let's say I'm a princess out like that it would print out blue Ferrari but notice that it's wrapped in an optional tag because for example if I passed in a key that doesn't exist right let's pass in like ASD two three eight then you can see there is no value for that key all right so that's why it returns nil so that's why when you access a dictionary and you pass in a key it returns to you an optional whatever data type that your value is so when you pass in a key into your dictionary to retrieve a value just expect that it is an optional and you may need to unwrap it and check if it's nil before using it okay so what if I wanted to let's let's label this so before we continue on this is declaring a new dictionary this is adding key value pairs and this is retrieving data and how do we update a value for a key well it looks exactly like this up here so you specify the key that you want to update the value for and here we can say that this guy now is a red Ferrari maybe it got a paint job or something so when you pass in this key from now on you're going to get this new value because this basically overrode whatever was there before and in order to remove a value remove a key value pair let's say you can do something like this you pass in the key to 3/8 and you assign it nil and actually that is going to remove the key value pair from your dictionary now I'm going to show you how to iterate over all of the key value pairs in your dictionary so why don't we just add a second key value pair in here so that we have more than one item to display okay and this one can be a green Lamborghini I think that's how you spell it I don't have one so I don't know for sure and now let's iterate over it wish I had one though iterate over it we use a for loop so we can say for essentially for each key value pair inside the dictionary do something and the way you specify this is you pass in we use what's basically called a tuple okay and so you can think of a tuple as a set of variables or a bunch of variables so we'll we're going to say license car in cardi B now the in key word shouldn't be new to you because you guys learned about the for loop in a previous Swift lesson so basically what should be new to you though is this this is a tuple so for each tuple in this dictionary we can do something what's gonna happen is it's going to grab each key value pair and the key is going to be inside license and the value is going to be car like that so now inside this for loop it's going to iterate twice and I'm going to find this key or this license inside this license variable and I'm going to find the car the string hair blue Ferrari or green Lamborghini inside this car variable and it knows even though there's no datatype associated with this tuple because my dictionary is string string for the key and the value I'm going to simply print a car like that and you can see that hmm it's just it's printing one key value pair here it's printing one car but I have two items and the reason is because we've actually removed a key value pair with this statement here so if I just comment this guy out we have our two cars and it's a red Ferrari because we changed it up here now I can also print out the license I can say you know license you know I can say something like car has a license like that has a license so that pretty much wraps up using a dictionary and you're gonna find that it will come in handy along side arrays in organizing your data so thanks for watching if you like this video please give it a thumbs up and please share it with anyone you know who's also interested in Swift thanks for watching I'll see you guys next time hey did you join my free Facebook community yet that's where I hang out along with a ton of other people learning iOS just like yourself I also post early access to all of my videos inside that group before I put them on YouTube you can also get help with any questions you're having visit the link below click on the join group button and I'll approve your request right away alright so I'll see you in there talk soon
Info
Channel: freeCodeCamp.org
Views: 404,722
Rating: 4.9371128 out of 5
Keywords: swift course, swift programming, swift tutorial, learn swift, swift programming language, ios, ios development, swift tutorial for beginners, swift course for beginners, ios programming
Id: comQ1-x2a1Q
Channel Id: undefined
Length: 189min 58sec (11398 seconds)
Published: Wed Jan 09 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.