Learn Swift Series (2019) | Chris Ching | Skillshare
Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
19 Lessons (3h 11m)
    • 1. 01 - Start Here

      21:35
    • 2. 02 - Data Types

      7:54
    • 3. Learn with Math Operations TUS

      3:30
    • 4. 03 - IF Statements

      16:13
    • 5. 04 - Switch Statements

      7:11
    • 6. 05 - Loops (Part 1)

      10:02
    • 7. 06 - Loops (Part 2)

      8:31
    • 8. 07 - Functions (Part 1)

      7:23
    • 9. 08 - Functions (Part 2)

      12:44
    • 10. 09 - Classes

      10:24
    • 11. 10 - Subclassing

      9:05
    • 12. 11 - UIKit

      5:29
    • 13. 12 - Initializers

      9:13
    • 14. 13 - Optionals

      21:33
    • 15. 14 - Properties

      6:41
    • 16. 15 - Designated & Convenience Initializers

      7:58
    • 17. 16 - Arrays

      15:55
    • 18. 17 - Dictionaries

      9:19
    • 19. Conclusion TUS

      0:21

About This Class

In this Swift tutorial series, you'll learn how to code even if you're a beginner with no programming experience.

The lessons are laid out in a step by step lesson plan that anyone can use to get a rock solid Swift development foundation.

We'll go through all the core concepts of Swift including:
Variables and Constants, Data Types, Properties, Functions and Parameters, Classes, IF Statements
And a lot more!

For all of the lesson resources, downloads and recap notes, visit this page

Transcripts

1. 01 - Start Here: Hello and welcome to my swift tutorial for beginners. If you want to learn swift programming, even if you've never coated before, then you're in the right place. I'll take it step by step, and by the end of this video, Siri's, you're going to have a solid foundation and swift programming. Now, before we dive in, I need to tell you about two things that are going to be critical for your success. Number one. You have to keep in mind that this is a journey, and I'll elaborate on this in a second. Number two is that you're going to have to get your hands dirty. Now these two lessons I've had to learn the hard way through my own failures. When I first started learning swift programming, I failed, and that was because I just kept learning and learning. And as I was learning, everything made sense in my head. But when I finally got to coding, I realized that I didn't retain a lot of what I had learned. That I don't want that to happen to you. So it's really critical that you practice and I'll help you along with that And the second thing is that, as with any journey worth completing, there will be ups and downs. You probably will be pretty confused in the beginning, but I guarantee you stick with it and you'll come out the other side. A swift developer. All right, now I know you're itching to get started, but just one last thing for your success. If you ever get confused or get stuck, you could simply leave a comment below, and we're going to jump in and help you out. Or you can join our free code with Chris Facebook community, where the team and I hang out as well as other Iowa's learners. All right, now that you have the right frame of mind, let's take a look at what your swift journey is going to look like. In this lesson. We're going to get you set up and oriented with the tools, and we're going to dive into our first swift topic, which are variables in the next five or six lessons. After that, you'll learn more swift. You'll do more hands on coding, and with each lesson you progress through, you'll be layering and building up your skills, becoming a stronger and Swifty er programmer. Then, from Lesson 7 to 11 you'll be learning more about how swift code is structured and organized and how it's actually used. Now, even if you just get up to this point, you'll have a pretty solid, foundational understanding of how the swift programming language works and how to use it. But we're going to take it even further. From that point on, you're going to continue learning new swift concepts and goodies that will enable you to do more and more with this wonderful programming language. Oh, and I forgot to mention in between these lessons all Sprinkle some challenges and exercises that I highly recommend you do, because it's gonna help you discover your hidden knowledge. Gabs. Okay, so with that said, Let's jump right in. Alright, So first things first. Where do you write your swift coat? Well, ideally, you want to be using a swift code editor because that way you can compile your swift code executed and take a look at the results. Well, Apple has released the tool called X Code, just for this purpose. Now, using this tool, you can write your swift codebuild your user interfaces and build APS across all of Apple's different platforms. And what's more, this app is completely free. The only drawback is that it's made for Mac computers, and there is no PC or Windows alternative. But if you're on a PC, it's not the end of the road for you. Because there are other alternatives, such as browser based solutions. You can type your swift code directly into the browser and execute it, and then take a look at the results. You're not gonna be able to it build apt this way, but you're still going to be able to use it as a learning tool toe. Learn swift programming language. I wrote an article explaining all of the different options that cold with chris dot com slash x code for Windows. Now, if you are on a Mac, all you have to do in order to get X code is go to the Mac App store and then search for X code here. You're going to see this listing here. Now don't be fooled by the low ratings. This is the tool that all of the professionals used to build ups on all of the apple platforms. It can be a little bit confusing at first when you launch it and from time to time it is buggy. However, it is the official apple tool. So it works and place nicely with the rest of the apple ecosystem, including submitting APS into the APP stores. So what you're gonna want to do is download and install X code, and you have to also make sure that you're running the latest version of Mac OS because if you scroll all the way down here, take a look at this compatibility section. If this doesn't say works on this Mac, you can you can actually click it and they'll tell you which version of Mac OS it requires . You want to go up here and check your version? No, of MCA less on your machine. And if you have a lower version, you can just search for Mac OS in the APP store right here, and it's gonna be a free upgrade for you. The only question is, does your machine support this latest version of Mac OS? Even if it doesn't and you can't get the latest version of X Code, I wouldn't let that stop. You use one of the browser based solutions because, um, you're still going to be ableto learn swift and practice with, even without X code. All right, so after you've installed X code, go ahead and click on open and that's going to launch ex Good for you. You're going to get this sort of welcome dialogue, and we're not going to create a brand New Exco project. Instead, we are going to get started with a playground, and that's just a lightweight little window where we can type in our swift code and executed to take a look at the results. It's perfect for learning Swift. If you don't get this welcome dialogue, you can always go up to the file menu, go under new and then choose playground. So if you have this welcome dollar, just click on Get Started with the playground were always gonna end up in this place where we're going to choose what type of playground we want to create. So under Iowa's she's blank playground, and you can save it anywhere you want. Make sure you remember where you save it so you can access it. I'm just going to save it on the desktop right here now, before we dive in here. Let's do a quick tour and let me show you all of the different elements of the playground. So obviously this big main section here is the code editor. This is where you will be typing in your swift code and there is some sample swift code here. We're not gonna worry about that just yet. I also have some line numbers, which makes it very easy for me to refer to the different lines of code. If you don't have line numbers and you want to enable them, just go to X code preferences under text editing, and you can turn those line numbers on or off. Now, you also notice that your when you hover your mouse under the different lines, this sort of blue play icon follows you. And when you drag it down and highlights all of those line numbers and blue well, when you click this run icon, it basically just runs the code up to that point. So if I drag it tow line number two and I click this blue button, it's just going to run that first line. But if I drag it all the way to the bottom here at line for and I run this. It's going to run all of the code of that point after line fort and you can see here a top . There's a status part which tells you the current status of the playground. It should say, ready for you, and that means it's going to be ready to aceptar code and run it. There's some options up here for some different views. The one I want you to click right now is this debug area. Haider show that the bug area and this is also referred to as the consul area when we're going to be testing are swift code. We're going to be out putting information into this, the bug or consul area. So I want you to make sure that you have this tray enabled and that you can see the output that's going shown there. This right hand side here is a preview of your lines of code. I wouldn't pay too much attention to this because from version to version of X Code and may look a little bit different. Where I want you to focus is in this debug area down here, because that should be consistent with what you're seeing in the video. Now there's one more thing I want to draw your attention to, and it's this button down here now. This will stop executing the playground. So if I hit stop, you can see that it enables this guy again, and you can also click this button. It's turned into a play button. When you click on this icon, it's going to execute your entire playground. If you hover your mouse here and you choose, you know a certain line of code to run the code up till that just gives you greater control . If you want to run like a segment of your playground rather than the entire playground, which is what you would click here now. Another thing is that if you click and hold this play button, you can see that there are two options. It's set to manually run, which means that every time you want to run your playground, you're gonna have to either click on this play icon or choose a line and hit this blue play icon. But if you click and hold it and change it toe automatically run. Um, every time you edit the code it's just going toe automatically execute your playground and update the results. Now, sometimes this can be a little buggy. Um, and as you can see here, it's running my playground. Sometimes this takes a long, long time for it to be ready again. And sometimes you know, when it's constantly running your playground like this, you're not going to see the update of results. It doesn't work as perfectly as we had want. So if you're having some trouble with, you know, not seeing output on your playground and seeing that this is continually running, then what you might want to do is just click, stop and click and hold it and change it to manually run. And when it says ready, you're going to be able to click and run your coat. All right, so now that you're a little more familiar with the playground and all of its controls in different windows now, we can actually dive into swift code. So when you're coding you want, have the mindset that you are giving the computer instructions on how to process data now take, for instance, a stock portfolio up. If you were building an app like that you'd have to write code to tell a computer where to grab the stock prices and then tell the computer how to manipulate that. Maybe come up with the percentage lost or percentage gained. And then you're gonna have to write code to tell the computer instructions on how to display that to the user in a table format. Another example. Take, for instance, a photo up kind of like Instagram. You're gonna have to write code to tell the computer where to grab the images right and how to display them to user. And if the user is taking a photo and trying to upload it to their account, you're gonna have to make sure that you have code containing instructions on how to take that image data from the user's phone and then where to upload it to some sort of file server and make an entry in a database. So when you're coding, you're always writing instructions for the computer on how to process different types of data, and in the next lesson, we're gonna talk more about different data types. But in this lesson, we are going to I'm going to demonstrate some simple pieces of data for you. So let's take a look at the playground right now, and we're going to ignore what's on the screen, right right up here, these couple of lines and I'm just going to show you some data. So here some number data, right, That's 123. Or we could have, like, a decimal number. That's another piece of data 0.7, or we're gonna have some piece of text and Texas surrounded by two quotes like that. And that's a piece of text. That's another type of data. Now the data is stored in the computer's memory, which is how the computer keeps track of where the data is and what it is. In order for us to work with it, we're going to need a way to reference that specific piece of data, and that brings us to our topic for today's lesson, which are variables in variables are a way for us to keep track of a certain piece of data . So now let me show you how to write swift code to create a new variable in order to keep track of a piece of data in memory. So in order to create a new variable. You type in the keyword V A R or bar, followed by a space, and then you can type in a variable name. Now you can name your variable anything you want, but it should be descriptive for the data that that variable is going to keep track of. So, for example, if I had a piece of data that was someone's first name, I might name my variable first name. And near the end of the lesson, I'll tell you some more best practices about naming variables. For now, let's write first name, and that's going to be our variable name. So just like that, we've declared a new variable called First Name. Now, at the same time, you can also give a piece of data for this variable to keep Chako. And we do that using the equals sign. So you're gonna write a space and then an equal sign, and then you're gonna write another space, followed by the data that you want this variable to keep track of. So since we named this variable first name, why don't we give it a piece of text containing the word Tom? So let's recap what this line of code does. So we've got a piece of text data, Tom, and we need a variable to keep track of it. So we're declaring a new variable using the var keyword. We're calling this variable first name and then we're using the equal sign to a sign that piece of text data to this first name variable. Now let's jump back into the playground and let's try this out. So I'm going to erase this sample pieces of data that we had here and you can see this line of code. Actually, this line of code which came with our playground, is exactly what we just showed in our slides. Except that this time the piece of data is hello playground And the variable name is str So here we're going to right in the line of code that I just showed you. Do you want to write V A R Space and are variable name is first name fault my space And then the equal sign and then space, followed by our piece of text data, which is Tom Now what we've accomplished here is that we've declared a new variable called first name and we've assigned the piece of data Tom to it. Now, whenever we want to work with that piece of data, Tom, we can just refer to our variable first name. So now let's try working with are variable. What we're going to try to do is output Tom down here in the console area. And there's a command called print followed by two parentheses like this and in the middle , you can give that command something to output into the consul area below. So why don't we try typing in first name in there and what we're going to do is you can either hit the execute button here or you can hit this blue button right there. So let's go ahead, Hit, Execute. As you can see here that we've successfully output that piece of data, Tom. So isn't that pretty cool? Your print command is saying that you want to print the data that is referenced by the variable first name. Now let's try working with another piece of data. Let's say var stop. Price equals 100. Hey, and now why don't we try printing stock price okay, and let's go ahead and click that line and we out put 100 down there now, just as enough side. If you're taking a look at the preview here and you might notice this slash and now this back slash and is just a line break or a carriage return. That's what puts that out. Put in a separate line down here in the console. Now what I want to show you is that you can actually reuse your variable so you don't have to declare it again, and you can just write stock price. You can change the stock price. It's a 50 right? You don't have to re declare it because you've already created that variable or declared it . So now down here, if I print out stock price, I hit the run icon. You can see that it's 50 where the the 100 go. While it's basically you've lost track of it because this line of code you're saying that now the variable stock price should keep track of the piece of data 50. So go ahead and give this try. If you're playing around, you might notice something like You cannot assign a piece of text data to stock price. Let's say uh, I just use Tom again. You can assign Tom to the variable stock price, and this is because the variable stock price is expecting number data only in the next lesson. When we talk about data types, I'm going to explain to you a little bit more about why this is. But for now, I just know that when you declare a new variable, as in Line five or Line eight here using the VAR keyword and you assign a piece of data to it. From that point on, when you try to reassign data to that variable, it can only be of the same type. So numbers or text, so stock price can only accept number data, and first name can only accept text data. So let's go ahead and erased this line here. So now you know how to declare new variables and how to assign pieces of data to the variable. Now there's something else you can use to keep track of data, and they're kind of like variables. These are called Constance now. The only difference is that when you declare a constant instead of using the var keyword, use the let keyword, So let's try declaring a constant here instead of using bar, I use let followed by space. And then I write my constant name. So this time let's say it's the last name and then I'm going to use the equal sign, and I'm going to assign a piece of data to my constant Can I just right Smith. Now what's the difference between a constant and a variable? Well, as you saw up here with a variable, you declare it once, like in line eight here and then later on, you can reassign a different piece of data to that same variable with a constant. You can't do that. Once you've assigned data to a constant, you can't assign anything else to it. In fact, if you try, it's going to give you an error. So let me demonstrate if I did something like that, X Code would immediately tell you that you can't assign something else to the constant last name because that's how constants work. So at this point, it might seem that variables are more flexible because you can do more with them, and Constance seemed a little more restrictive. That's true, but there are instances where you would want to use constants instead of variables. In fact, if you want to keep track of a piece of data and you don't intend to change that piece of data, then using a constant would be preferable. I wouldn't worry about it too much for now. As you get farther into your swift journey, you're going to understand when to use variables versus constants. And furthermore, when you're coding an app, an ex code has detected that you haven't changed the data in your variable. It would suggest for you to change that variable into a constant and then, at that point is just a matter of changing the var keyword to the let keyword. But for now, I just want you to know that there are something called Constance which work like variables . All right, in The last thing I want to Talk to You About is best practices for naming variables and constants. And I mentioned before that you do want to be descriptive with your variable and constant names so that you know what kind of data they hold. But there's a balance that because you don't want your variable and constant names to be too long because then it can also be really hard to read. And you don't want them to be so short like str or even, maybe just s because then you don't know what kind of data it holds, right? So I would say 1 to 4 words is ideal. And furthermore, if you had something like three words like very first name or something like that, it can still be hard to read. So a best practice is to use camel casing and Campbell casing is just where you have the first word having a lower case letter and then every subsequent word, starting with a capital letter. And you can see now that it is a lot more easy to read versus all the work helps. Okay, so before moving on to the next lesson, let's do a quick recap. You learn that variables are used to keep track of information. You learned how to declare any variable. You learn how to assign data toe a variable. You learn about naming variables and camel casing. Finally, you learned about Constance and how they're like variables, except that you can't reassign data to them after the first assignment and I know that's a lot to absorb. But that's why I have a practice video for you, where we're going to go through a couple of exercises for you to get hands on and dirty with. I also have a set of recap notes that you can download now the links that both of these resource is our down below in the description below the video. All right, great job with lesson one. I'll see you in lesson to 2. 02 - Data Types: Hello and welcome back to my swift tutorial for beginners. This is Lesson two. If you missed lesson one that I highly recommend that you start their first now back in lesson one. You learned all about variables and constants and how they're used to keep track of the data in your app. Now, the data in your app can be a simplest text or numbers, but it can also be complex, such as photo data or maybe employee records in a company database and swift. There are different data types to categorize these different kinds of data, and that is today's topic. So let's dive in. So I've got a brand new playground here, and I want to show you something that I did a little preview for you in the last lesson. So here we have a variable called str and we've assign a piece of string data or text data into that variable. And I showed you last time that you're not able to do something like this when you re assign data to variable. You can't change the data title now. Data types were something that week lost over in the previous lesson, but that's what we're going to talk about here today. So in Swift, there are different types of data. So far, you've been introduced to strings, which is essentially just text data. And I know that's a little bit of a weird name for text data, but you can think of it as a string of characters. At least that's how I thought of it when I first started. And then it is for integers of these represent whole numbers, positive and negative. And then you have your decimal numbers. You actually have two data types to represent your decimal numbers. We have float, you have double. The only difference is that double is more precise, so we can actually store ah longer decimal numbers. And then lastly, for this slide, at least we have Boolean or just pool. And this represents true or false data. It's perfect for data where there is only one of two options. So those aren't the only data types and swift. However, they're probably the most common that you'll work with for a while. And also, when you get a little more events, you're going to be able to create your own data types that are more complex than the ones that I just showed you. Just as a quick example, you might create a data type called person, which includes a lot of information like your age, your hair color, your eye color, your ethnicity, your likes and dislikes and all of that sort of stuff. That's a lot of data, but it's all related to one type, which is a person so quick. Example. Quick preview. But for now, let's just focus on these common, simple data types. Now. What I want to do is I want to focus on the practical side of data types, so I'm going to show you in terms of declaring variables and constants how you would specify the data type for your variable or constant. So in the last lesson, you learn that in order to declare a variable, you would use the bar keyword, followed by the variable name. And for Constance, you would just use the let keyword, and then you would use the assignment operator in other words, the equal sign to assign some sort of data into that variable or constant. Well, one thing that I did leave out was an optional part of this variable or constant declaration. And that is that after your variable or constant name, you can put colon followed by the data type that you expect this variable or constant to keep track of. So in this example, we are assigning some string data to are variable. If I were to explicitly declare that my variable can only hold string data, I would put Colon followed by string, which is the data type name. So now let's take a look at our playground again. Why up here in this variable declaration? Was there no data type specified? Well, that's because you don't really have to do it. If you don't specify the data type, what's going happen is it's going to take on the data type of the first piece of data that us signed to it. So if my first piece of data was actually an integer like 100 then my variable STR would now be an integer data type of variable so that you can see that this line actually doesn't produce an error, because I can reassign data to my variable as long as it's the same data type that it took on in the first place. Now, just a quick note. Why is it that if this variable is an int type of variable, why is it that I can't assign a piece of string to it? What's happening under the hood? Well, the thing is, different types of data are stored differently in memory. And so when you declare a variable, str and you say that it should store integers well, To put it in simple terms, it's just going to be set up to store integers. If you were to say that that variable would store string data, it's going to be set up a different way. Now there is a data type, which gives you more flexibility in terms of storing different kinds of data. But that's a topic for another date, and the second thing is that it actually helps you as a coder because imagine if your variable can store any kind of data. You don't know what to expect, but the fact that you know this variable str can only store numerical data or integers to be specific. That sets your own expectation as a coder. Sometimes having too much freedom is not a good thing because it offers more opportunities for errors. And when we're programming and when we're coding, the greatest enemy is actually us making mistakes, either in our logic or in the way that we've coated something. So that's a little bit about why their data types. Now let's do some quick examples of some of the data types that we've talked about. So we've got str here. So let's leave this as a strength, okay? And let's do Let's do another one called a. I know I'm not following my same rules about having descriptive variables, but you know what? We could do that. Let's call call into your do 100 do a look, and that could be like zero point one or two double. You know I'm not, and you could do far cool. This is the data type for that. And then this can be true or false. And like I mentioned before, you don't have to explicitly specify the data types like this. It's going to take on the data type of the first piece of data that you assigned to it. Now this part is a little tricky because afloat and double both represent decimal numbers. It's just that double is born precise. So if you remove that data type, what kind of data type is float and double or sorry, these two variables. What are they? Well, it turns out that double is the default decimal data type for Swift, so this one would actually be a double data type. That's what the system is going to treat that as. And then Boolean is just bullying removed that it's going to see true, and it's going to make this variable Boolean type. Okay, so before moving on to the next lesson, let's do a quick recap. In this lesson, you learned about the most common data types that you'll be working with. You also learn that you can explicitly specify the data type when you declare your variable or constant. And if you don't do that, the variable or constant is going to take on the data type of the first piece of data that you assigned to it. And in the last lesson, I did forget to mention that I have a swift cheat sheet available for you to download and reference so you can have quick access in case you forget the syntax or maybe data types or anything else, and it's very handy to keep besides you as you're learning Swift 3. Learn with Math Operations TUS: in this quick video, I'll be going through some of the basic math operations that you can do with constants and variables and just in general equations. So why don't we do pretty basic stuff right here and add two numbers together using the addition operator? So this is probably what you'd expect, you know. But there are a couple of them that you might not realize, so that's why it's important to go through it. There's plus, there's minus. You're gonna get zero from not. And there's also multiplication using the Asterix and There's Division. And then you can also change these together. If that wasn't obvious, so we could do something like this. Okay, so you get eight. Alternatively, we can use the power function to do exponential. And that, that is that Looks like that. And it accepts two doubles, so this would be the base, and this would be to the power of we can do to and three. But notice that it accepts a double, right? So if I try to run this right now, I'll still get eight. So that's fine. I was just worried that these guys were actually integers so these were detected as industry types instead. But that's that's awesome. They're square root just to show you a couple other ones and some that you might not be familiar with. There is ceiling, which basically rounds up. So if I just had, let's say Marty is equal to 5.44 point five. But D in there, see what we get. You know that that would be five, right? Cause it rounds 4.5 up. And then there's also floor, which runs down. If we do that, you get four from 4.5 and next I want to show you the increment or decker Ament shorthand, because that might not be immediately obvious, and I tend to use it a lot. That's very useful. So let's say you wanted to do something like a equals a plus one because you want to increment a by one so you'd get three, right? So you're basically taking a adding one to it and then reassigning it back to a So if I printed this out Well, yeah, we can just look at the preview window here. If I ran this, you would see three here on the side. Now, another shorthand way of writing. This is just to go. A plus equals one like that. And this would give you for now because we're incrementally it again. The reason this shorthand exists is because you tend toe do that a lot. When you're expressing your logic and your writing algorithms in your code incrementally and Decker menting tends to happen a lot, so that's why that exists. You can also deck criminal like that. So documenting by one now they would be three, right? This is equivalent to writing a equals a minus one. And this is equivalent to writing a equals a plus one. So if you see me doing that in code now, you know what it means. 4. 03 - IF Statements: Hello one. Welcome the lesson three of my swift tutorial for beginners video Siri's. Now that you know all about variables, constants and data types, it's time to start having some fun in this lesson. We're going to talk about a staple construct that exists in all programming languages in some form or another. And yes, I'm talking about the if statement, let me show you what they're all about. So the reason I'm so excited to show you how to use if statements is because starting from now you're gonna be able to write code that can make its own decisions. You're going to be able to write some app logic. So why don't we start here with a constant on? We're just gonna use a letter. A will say a equals 10 and I'm going to print is string down here. Let me just open up the console so can see something. And I want to say, uh, that's a A is less than 10. Or how about is less than yeah, I'll do A is less than 10. Now. This is going to print regardless, right, because, well, first of all, I have to run my playground there we go. A is less than 10. Well, this actually isn't true, right? Because A is 10. So it's not actually less than 10. And in this case, I don't want this to show up. Well, the problem is that that line of code is there, right? So it's gonna be run and it's gonna show up. What we can use here is an if statement so we can add and condition. And we can say that we only want to run this print statement based on some sort of condition that we contest. So let's see how it can do this with an if statement. So it all starts with the if keyword followed by a space and then your condition, which we're going to test. Also, you have to write that condition in just a second before now let's continue with the rest of the if statement, they have a space, and then you're going to have a set of braces or some people call it curly brackets. Inside those braces, you're going to have the code that is on Lee going to be run. If the condition equates to true. If that condition turns out to be false, then the code inside of your braces will not be running. So now let's jump back to the playground and see this in action. So I'm gonna use that if cure here followed by a space. And the condition that we want to test is is a less than 10. Right? So we're gonna do a and this is the less than operator it's going to check. Is the left side less than the right side? So on the left side, we've got eight on the right side. We're gonna put 10 right, followed by a space, and then we're gonna open up an opening brace, and I'm going to go under the Prince Damon and close that brace. No press tab here. So we've got, uh, our line of code inside of an opening and closing brace. And this is our condition here. So it actually doesn't matter if you want to put your brace down, Hero appeared to make sure there's a space in between your opening brace and your condition . Now, let's try to run our code and press this blue button here this time and you can see that now the console is empty. So what happened here was that it checked. The condition is less than 10. And because a is 10 it's clearly not less than 10. The condition equated to false. And so it didn't run the code inside here. Now, why don't we make that condition true? Now, all I need to do is say, is a less than or equal to 10. In that case, this condition would be true, right? Let's press run, and then you can see it printed down here. All right, so that's really cool, because now you can write code that can be run based on a condition. However, often times we've got multiple choices that can be made. Like, for example, do you want a big Mac or do you want chicken McNuggets? So we're going to do this using another feature of the if statement called on else. If Klaus, let me show you how that works. So right underneath the closing brace of your statement, you can put the keyword else space if and then you would have another condition, then followed by another set of braces. Now, what's gonna happen here is that it's going to check your first condition in your if branch . If that happens to be false, it's going to skip right down, and it's going to check the condition in your else if Branch. If that also happens to be false, then it's just going to skip again, and it's not gonna do anything. However, if one of those conditions were true, then it would run that branch of code. And keep in mind it's on Lee ever going to run one branch of code. So imagine yourself standing in the middle of Crossroads. There's two paths, one on your left and one on your right. There's only one path you can go down, right? So that's kind of like how the if statement works, except that it evaluates the conditions from top to the bottom. So the first condition that is true. It's gonna run that block of code, and then it's just going to ignore everything under that if statement. So let's jump back into the playground and let me show you how this works so we can say something like, Let's make a 20 now, right? So we've run this code right here. That's not going to run because it's false. Now we're gonna use else space if space and let's say is a greater than 15 and then I'm going to print A is greater than 15 right? So if you run this if statement, what would you expect to happen? It would evaluate this right. And since that's false, that's going to skip down and it's gonna check this, which happens to be true, and it's gonna print that. So let's give that or run. We've got a is greater than 15 printed down here. Now, let me show you something else. What if a was five and then we changed this condition like that? So this condition test is a less than or equal to 10 and this one is is a less than 15. They're both true, right? I guess I'm gonna have to change this to or else it doesn't make sense so that both of these conditions are true. What would you expect to happen when I run my playground right here? Well, it evaluated this condition which happened to be true. So it jumped into here this fork of the road, right, And it executed that branch of code and it ignores everything else. It doesn't check the second condition at all. Eso that's really something to keep in mind. So another cool feature of the if statement is that you can stack these else if clauses. If you've got more things to check, more conditions to check, you can just add them to the bottom like that. So if a is greater than 30 I'm just making stuff up at this point. But you can keep going and keep going. The only thing is that you don't want to make it to too long. There is actually another kind of decision tree sort of structure that you can use, which I'll tell you in the next lesson. But in this one, just keep in mind that you can check multiple conditions, but you don't want to abuse it. Now I want to tell you about this last feature of the if statement, which is the else clause. So the else clause is kind of like a catch all bucket. If none of the conditions at the top evaluate to true, it's gonna keep checking from the top down, right? If none of the conditions above the else branch is true, then it's just gonna end up executing the code inside of the else branch. So the way you include this else branch in your if statement is you used the else keyword, and then you just open a set of braces. There's no need to specify a condition, because remember, the point of the else branch is to execute some code, just in case nothing above it got executed. So let's jump back to the playground and take a look. So we've got a is less than 10 a is less than 15 and a is greater than 30. Well, there's a gap right in between 15 and 30. So if I said something like, you know, A is equal to 25 and I ran the code right here, nothing would execute because none of this is true. Let's just print something here. Print A is greater than 30. All right, so nothing gets executed right here. But if I add and else branch right, open up a set of curly brackets or braces Here, uh, is something else, So why don't we give that a run and you can see that indeed, it falls into, uh, this catch all branch of code. So Now I've shown you all of the basics of the if statement. However, it can get a lot more complex because your conditions inside your if and else if branches can get really complex Let's say we introduce another variable here. Let B equals 10. You can start to change these conditions together. So, for example, if I wanted to check that a was less than 10 and also that B is greater than five and I want both of these conditions to be true. In order for that branch to be executed, I can use the double ampersand symbol, which represents that I want both of those conditions to be true in order for that branch to be executed. So it's to be is that I say greater than five or less than five less than five. Um and this actually would not be true, right? Because is 25 B is 10 So it's gonna skip here, So why don't we modify this a little bit? Why don't we say a is less than 10 end B is greater than five. So, while this part is true, let me just run this and I'll show you what output is right. It still falls into here. Why? Well, although this is true, this is not true. And when you use this double ampersand sign right here, you're basically saying that you need both of those conditions to be true in order for the whole condition to be evaluated as true. However, if you don't care and you only want one of those conditions to be true, you know, either or then you can use the or operator, which is actually a set of double pipes that I don't know if they're called pipes, but this key is on on my keyboard, at least is above the return key, and you have to hold shift to get them. So double pipes will give you the or operator and let me run this code. Show you what that looks like. So we come into here and execute this. Now, this this statement is a little bit misleading now, so I'm just gonna call it Branch One fresh, too French three. And let's say cattle, All right. So I can run that and show you that this gets printed because we're using the or operator, either. If either a is less than 10 or B is great and then five. Then we're good. We're gonna execute that branch, and that's exactly what we get here. French one. Now I'm going to blow your mind further because we can further chain these things. So what you can do is you can wrap this condition right in a pair of parentheses like this , and then you can say And let's say we've got 1/3 1 and let's say we want Either be is greater than five or is less than 10. And you know, C is equal to one right? And if we won that it would come into here because this part evaluates the truth, and this also evaluates to true. Now we can even go further and weaken. Start wrapping that in a pair of parentheses, and you contest as many things as you want and you can build this massive condition. But just keep in mind that the more things you put in there, the more complicated it's gonna get, and the harder it is for anyone to understand. I want to draw your attention to one thing, though, and that is this equality operator here. When we're testing equality. We don't use the single equals operator here because remember, that's for assignment. When you do that, you're trying to assign one into the constant C. When you want to test for quality, use double equal signs. And when you want to test for inequality, you can use exclamation mark equals. And that is testing that C is not equal toe one. So if I run this code right here, I would get catchall. Reason is because although this evaluates to true, this does not evaluate to truth and because we're using the end operator there. We need both sides of that to be true. If I change this to an or and I ran it, we would get French one. Because even though this isn't true, this is true. So it's kind of a little bit of logic there, which is fun to do, and it takes a little bit of practice to wrap your head around. Now what I wouldn't do highly highly recommend that you do not do this is don't memorize thes keywords. Don't go and try to memorize Oh, I need the if keyword I need a condition here. All the operators I can use. Don't do that because I'm going to introduce more keywords to you and more syntax to you. And it's not gonna be fun for you to try to memorize it. And it's not practical. Talk all about being practical, and what I want you do instead is spend 30 minutes. Um, take a look at the worksheet for this lesson. Try out the if statement on yourself on a playground and in 30 minutes of learning, you're going to learn a lot more, and it's going to sink into your head a lot more. You're gonna remember it a lot more than it would if you had trying to memorize this. So how to recommend that you do instead of trying to memorize? Remember, I have a swift cheat sheet and worksheets for you to practice what you've learned in today's lesson. I highly recommend you go through that because I don't want you to make the same mistake that I did when I first started. Now let's do a quick recap. You learn that you can use the if statement in order to execute code based on a condition. You also learn that you can use the else if clause to specify alternative branches of code to run based on other conditions. And finally, you have the else clause to run some code. If all of the conditions above it are not met now. One key thing to remember is that the conditions will be checked from top down and the first condition that is true. That's the branch of code that is going to be executed and the rest of your statement is going to be ignored. All right, great job on this lesson. Just click over to the next one and we'll talk there. 5. 04 - Switch Statements: hello and welcome the lesson for of my swift tutorial for beginners. Now, in the previous lesson, you learned about how you use the if statement to run code based on some conditions. Now, sometimes when you really get into coding, you might find yourself ending up with a giant if statement with so many branches that it's going to give you a headache when you see yourself going down this path, I want you to stop and consider using a switch statement, and in this lesson I'm gonna show you exactly how to use that. So the first thing I want to mention is that there is a swift programming language guide and probably should have mentioned this in less and one. But better late than never. I'll add a link to this guy in the description below the video. Now this contains kind of a walk through of the language that actually it's more in depth in that, um, it is basically everything you'd want to know about the swift programming language. However, it is quite a lengthy read. But if reading is your thing, then I would highly recommend that you go through it, especially if you come from another programming language. It's gonna be very useful for you to skim through it, see how the structure of the language is the syntax. But if you are an absolute beginner to coding, if you never coated before this is your first exposure to it, then you might get a little bit confused, however, still a great reference in compliment to what you're learning here in the video lessons, so definitely check it out. So I just wanted to point out where we are now. I'm not following the exact order that they have listed out here because I feel like the way that they have laid it out is a very slow build up until you can actually start using the language of having fun with it and building things. And so, the way that I've laid out this lesson plan for you in this video, Siri's you can be. It's very practical, and you can start coding and start tinkering and having fun sooner. So I just want to show you where you would find some of the lessons that we've gone through . So in the previous lesson we talked about if statements that's under control flow, and there's also this little drop down here is, if you pull this guy down, you could jump to different sections. So we are at conditional statements right here so you could see the if statement gives you a couple of examples. So it's, you know, it's really good supplementary material toe what we've covered. But in today's topic, I want to talk to you about the switch statement, which is right here. So I just want for you to take a look at the syntax here. You'll notice that there is the switch keyword here. And then there is some value to consider and then a set of braces and inside there's thes case and these default keywords. You know what? I'm going to show you how it's used inside of a playground and going to use that example. So you know it's gonna be a lot easier to understand, so let's go ahead and do that. So let's pop open X code here. Let's get started with the playground and I am just going to switch played down and I say this on the desktop. Let's just minimize this guy. What's destruction? I declare a new constant here. And let's say that this is a character. Eso Why don't we call this a and we are going to assign it? Uh, a little sign and a Let's call it character. This call a C h. R. Now, if I wanted to test this constant and see if it was equal to a I could do something like this. If chr is remember, we use double equal sign for equality, testing, equality. I mean, you know, I could print the character is a And then if I wanted to go through all of the letters of the alphabet, I could do else. If you know, you get the picture right, it would be a giant if statement not recommended. But this is where the switch statement would come in handy. So why don't we just quickly take a look at the syntax? So just like you saw in the language guide, you start with this switch keyword, then followed by the thing that you want to check in our example in the playground that was the constant named chr. And then you open up a set of braces and then inside the braces, you put all of the things that you want to check for, and each thing that you want to check for is preceded by the case. Keyword. So it would be case whatever you want to check for first, followed by Colon and then the code that you want to execute. If that case is true, followed by the next case and so on and so forth and at the very bottom, you have a default case for when none of the cases match, it's going to hit the default case and run your code there. Now let's jump back to the playground and see this in action. So let's erase this if statement and instead use a switch statement se switch. And actually, you can use auto complete uses. Press enter like that and it's gonna come out with all of the cases for you. Or you could type it out for practice so you can see immediately it. It's come up with this syntax for me, which is really handy, because I can actually hit tab on my keyboard and jumped through the different things that I have to fill in. Well, I guess it stops right there. Let's change the value for chr and the pattern that I want to check for. You know, the first case would be a right and the coat that I want to put here with this is a right and then default might be This is all that. So let's run this code and see what happens. So, as expected, it hits this case and it prints and eight. Now, what if we wanted to check for something else? Print This is. And if we change that to be and then we run it again, you'll see that it skips this case and it comes down here and prince distance that now one additional cool thing I want to show you is that you can actually combine cases. So let's say for cases B and C, I want to execute the same block of code. So I want to say, this is this is a B or C. So I would just put a comma here, and I can put the other thing that I want to check for. So if CHR is a B or a C, then this code is going to be executed. Eso as expected, it jumps down here, So this is pretty much it for a switch statement. It's pretty easy to use, to be honest, and it's a lot easier to read them. A giant, if statement When do you agree now to get more practice using switch statements, I highly recommend that you get the worksheet. Just hop on over to the resource is page for this video, Siri's to download it. All right, we're starting to really get into the exciting stuff, so go on and click over to the next lesson and I'll see you there. 6. 05 - Loops (Part 1): Hello and welcome The lesson five of my swift tutorial for beginners video. Siri's Now In the last two lessons, you learned how to write code that can be executed based on some conditions. Now let me introduce you to something called Loops. Loops allow you to repeat a block of code multiple times, and while this might sound a little bit boring and repetitive, it's actually quite useful. Let me show you how they work. So I'm going to demonstrate for you the four in Loop, and this is going to allow you to loop a block of code for a set number of times. Let's jump into the playground that I have prepared. Well, I haven't actually prepared anything cause it's a blank playground. But let me present to you this dilemma. So if we were to print hello in the console and let's say I wanted to print this five times now, I could just write five lines of code like this. You know, you get the picture, but we can use a for in loop to condense this code into just a couple of lines. And let's take a look at the syntax for a for in loop. So true to its name, the keywords to use our four. And in you start with the key word for followed by some sort of variable name. Now you don't have to use the var keyword here. You just give it a name and then you write in and then you specify a range. So they're a lower range, followed by three dots and then an upper range. And I just want to mention that it's an inclusive range. So if you're ranges Oneto five, it's gonna loop from 1 to 5, and that would be a total of five times. And then you follow that by a set of braces. Inside the braces is where you put your code, and that code is going to be looped for whatever range that you've specified. So I know that this is yet another set of keywords and another sort of syntactical structure that you have to remember. But remember what I said. Don't try to memorize anything as long as you do the exercises and worksheets after each of these lessons, and you just I spent 15 minutes even just trying it out and playing around with it. You will remember the keywords to use and the structure of the foreign loop. You don't have to memorize anything. So that is really the way to go. And don't forget, I do have a cheat sheet for you to download on. The resource is Paige for this video series, which you can find the link to in the description below the video. So have that cheat sheet besides you. And if you ever forget, you just refer to it. All right. Now let's jump back to our playground and let's take a look at doing this for in loop. So I'm going to just create my right up here. So four and then I'm going to use the variable name counter in right. And I specify a lower toe upper range, and I'm going to do one dot, dot 1.0.5 and I'm gonna put my braces. So inside these braces, we're going to put our print Hello. So let me erase four of them. Cut that one, and unless pasted inside there, and we're gonna run our code Boom. So now we have hello five times. How easy was that? Sure enough, it's run our code from one the five. Now the question is, what is this counter for? What is this variable name for? Well, the thing is, for each iteration of the foreign loop, that counter refers to that number. So in the first iteration of the loop counter actually contains one in the second iteration counter contains two and so on and so forth. So let's say I wanted to print out the counter. Maybe I wanted to print out numbers 1 to 5. I could pretty counter. And then I can run that. And then you're going to see 12345 output instead. No one cool thing is that you see that there was this yellow warning here and that was X code just telling us that Hey, if you don't need to use that variable, then you don't have to specify it. But since we started using it in this print statement, that warnings gonna wait. So let me tell you what that warning was all about. Why don't we go back to hello and then that little warning is gonna come back, and it's telling us that this counter was never used. Consider, and this is kind of cut off when you see if I can show you consider replacing it with an underscore or removing it. So what? What happens is that if you actually don't need to use that sort of counter, you can replace it with an underscore like that. That's gonna be fine. That's perfectly valid for in Lupus Index. Now, I want to show you one more thing that might get you tripped up. When you're working with loops, why don't we add this counter variable back because we're going to need it. So let's say I want to display or let's say I want to add up all the numbers from one all the way up to five and I want to get the sum of all of those numbers. You know, you might do something like this. You might say you might declare bar some equals zero and then remember that this counter contains thes numbers for each iteration, right? So I might want to do something like this plus equals counter. And I think this is the first time you've ever seen the plus equal operator, right? Like this. This is just an increment operator. So what we're actually saying is basically add whatever counter is added to some. So if some of 10 encounters five, well, some is now gonna be equal to 15. So another way to think about it is that it's equivalent to writing some equals sum plus counter, because I kind of just like a shorthand. All right, so in every adoration were basically adding one and then adding to an adding three. And we're collecting it inside this variable something. So what I want to do now is just print some and now let me run it. What would you expect to happen? Let's take a look. Get 1234 and five. Well, that's not what we expected, right? Why is that? Well, let's take a look. So in federation number one, we declare a very well called some. We've set it to zero, and then we're adding one, 20 and then we're printing that. And so we get one while in generation number to counter is now too. And then we are declaring some and setting it to zero. So we're essentially adding to 20 just to and so it prints. Some would get two and so on and so forth So the problem is that in every iteration of the loop we are declaring some and we're setting it to zero. So we're not really getting that addition of the counter through the federation's like we want. And if you notice you might say, Why am I able to declare some so many times right? Because in the very first lesson, I told you that when you declare a variable appear like this and like str, you don't need to re declare it in order to assign it something else, right? So I can assign Tom toe str appear and that would be perfectly fine. However, if I try to declare str again you know, like this, I'm going to get an error invalid read declaration of str where you can't do that. So why is it that I can do that here, right in every single it aeration we're declaring Variable called some and setting it to zero? Well, the reason is because every adoration it's almost like a clean slated. There's no recollection of what happened in the previous generation, so that's why that's happening. Essentially, we're resetting some every single iteration what we want to do instead to get the desired effect is that we should move this declaration out here and set it to zero. And then inside each iteration, we are essentially just adding the counter to some. And we are going to get the desired effect if we do it this way. So outside here, I'm gonna print some Let's stop it, run it again. And so we get 15 and that's the numbers from 1 to 5. All added up. Now, as you can see up here, we've declared some. We've set it to zero, and down here in the for loop in the first iteration counters one. So we're adding that to zero, and so some now is one. And in the second, liberation weren't not resetting in some counters to this time. And we are adding to toe once we get three and then so on and so forth. And then the loop ends after five iterations and then we print something. So that's why we get the single number here. So I just want to go through that quick example to illustrate kind of how loops behaved because I know a lot of beginners who get tripped up with something like that. All right, recap time. So use a for in loop to execute a block of code for a set number of times, and each time your code runs is called a federation of the Loop. Now be sure to practice with the worksheet for this lesson, because loops are powerful stuff. In the next lesson, I'll show you some other kinds of loops. Just click on over there for the next lesson, and I'll see you there. 7. 06 - Loops (Part 2): hello and welcome to lessen six of my swift tutorial for beginners video. Siri's Now in the last lesson you learned about the four in Loop, which lets you execute a block of code for a set number of times. Well, there's another kind of loop to actually that allows you to loop your block of coat indefinitely until a condition is met. These kinds of loops are awesome when you don't know how many iterations it's gonna take to get the job done. All right, so let's dive in and see how they work. So in this demo, we're going to go through two types of loops that are really good to use when the number of times that you need to loop for is unknown. So the 1st 1 is called the while loop, and this loop checks a condition to see if it's true, and then it's going to run your code and then check the condition again, and then when your code and check the condition again. That's too quickly. Take a look at the syntax for this, so you start with wild keyword and then you have a condition, and then you have a set of braces and then inside the braces, you have the code that you want to loop. Now. Notice that the condition is up there at the top before it even execute your code. It's going to check the condition first, to see if it's true. Kind of like an if statement. If that condition is not true, then your code is not going to be run at all, let alone loop. Let's jump into the playground now and let's do a demo of the wild loop. So I've got this guy right here, brand new playground fresh out of the oven. So far, let's say she's counter is equal to five. And then let's say that I want to look through the same example like we did before. We're going to print hello. And what we're going to do is say, while counter is, uh, less than or story while counter is greater than zero, I'm gonna print hello. Now, before I finish writing this in text for this wild loop, you can see here it's telling me you need to set of braces. But before I finish writing this index for this well, I just want you to notice one thing. So first is going to evaluate this condition and it's true, right? You can see that counter is equal to five and five is greater than zero. So it's true. So it's gonna print Hello? It's gonna loop and check the condition again, and it's gonna be true again. So it's gonna loop, and it's gonna keep looping infinitely until we get a crash. There's an overflow eso let me demonstrate that I would not recommend this if you've got a slower computer and I'm not even sure if minds very fast So it's just gonna keep going. Maybe now ex code has something where it's oh, I have to run my code. Let's do that so you can see it just it's going bonkers, right? So I'm gonna stop that right now. It's not stopping. Okay? Yeah, it's not stopping. My computer is kind of going haywire right now. Eso what you want to do actually is inside this one. You want to write some code to actually make it so that this condition can be false. So if we print it now, Sorry if I can actually get this. Uh, yeah, So you see, I e wouldn't recommend you to do this, but we can still walk through the coat. So while that's running my playground, let me just explain what happened here. So I basically created a while loop that ran on indefinitely until I added this code here. So this code decker mints the counter by one, just like you saw the other one, which was plus equal one. And that would actually add one to the counter. This one minus is one from the counter. So it starts at five. Right? So the first iteration would be five and in print. Hello. And then it would turn that counter into four because a decorative meant by one and loop again and four is greater than zero loops. And then this line would set counter to three. And then I'd go on and on and on until hits zero. And then zero is not greater than zero. So that is actually allows us to exit the loop. I knew that was pretty bad idea. So I'm gonna try and stop this. There we go. So can I run this now? I think I broke it, so I'm going to actually quit X code right now see what we can do here. Nope. Alright, guys, we're back. So all I had to do was quit X code and restart X code and run my playground again. Uh, let's run it here. All right, so we've got our hello five times, which is great. Now we can talk about our second type of loop, which is the repeat while loop. So let's let me show you where that is. Just scroll little down further here. The repeat while duke and let's take a look at the syntax for this. So here you have the repeat keyword, followed by a set of braces inside the braces, you have the code that you want to loop. And then what's noteworthy is that behind the closing brace, you have the wild keyword and then the condition. So notice how the condition is at the end of the loop instead of the while loop where the condition was at the top. So essentially, what happens here is that your coat statements are going to be run at least once. And then after it is run, it's going to check the condition. And if the condition is true, then it's going to repeat and loop it. So it's different from the wild loop, which checks the condition first. And it might not even run even once if your condition isn't true. So let's go back to the playground now and test out the repeat while loop. So I am going to declare, Say, counter to equal five again. And I'm going to use the repeat keyword a print. Hello? And then here I'm going to deck rem int my counter just like we have up there. And I am going to say, while counter to is greater than zero So phone while let me do Yeah, hello from while loop from Pete while and let's do that. So what happens is that we get five of these printouts from the first wall loop and we get five of these printouts from the second while loop right, just like we expected. However, what if I changed counter to, um, that's a negative five changed country to negative five and run it Well, you look at that. The wild doesn't even run once, right? Because it checks the condition first. That's not true. It's not going to run your coat. Skip this one it's going to print it out first, and then it's going to realize that a negative five is not greater than zero. So I'm not gonna repeat I'm not gonna loop. So the one that you use really depends on the situation and what you're trying to accomplish. If you're writing some logic that you know, we want it to happen once and it only conditionally repeats, then you want to use the repeat while loop. However, if you want your co two Onley, be run when certain conditions are met and as long as that condition is still true, then you use the wild. All right, let's recap you learned about the wild loop and the repeat while loop that lets you execute a block of code and loop it indefinitely until a condition is met. Now, the while loop checks the condition first before executing the block of code and then looping and the repeat while loop will execute your block of coat first and then check your condition to decide whether or not it should repeat for another iteration. You're doing amazing so far. All right, click over to the lesson seven. I'll see you there 8. 07 - Functions (Part 1): Hello one. Welcome to my swift tutorial for beginners. In this lesson, you're going to learn all about functions, what they are and how to use them. Now functions are a critical part of the swift programming language, especially if you're going to be building apse with Swift. So let's get started. Alright, so I've got a brand new playground here. But before we dive into right, our first function, let's define what they are at the most basic level. Ah, function lets you take a block of code and give it a function name. And whenever you want to execute that block of code or basically run that code, you call that function name. That might seem really simple, but the powerful aspect of it is that it lets you organize your code into smaller chunks of code for specific tasks. So that way, if you wanted to perform a specific task, you could run that specific function. Now they can get pretty powerful with the ability to give the function data to have the code, take that data, work with it and return the result back to you. But in this lesson, we're just going to take a look at the basic function, so let's take a look at how did you find a function first? So it all starts with the funk keyword or F u N C. Followed by a space and then your function name, so you can give your function any sort of name you'd like. But you should be descriptive about what that code inside the function does, so that when you want to perform that task, you know which function to call following the function name. You have a pair of parentheses. Now, in the basic function, we're not going to have anything in between these parentheses. But in the next lesson, we're going to learn how to add input parameters and in between those parentheses is where you would specify those parameters. For now, we're just going to leave it as to parentheses, with nothing in between them. All right, and then next up we have a pair of curly braces, and in between the curly braces is where you would define your code for that function. Any call you right in between those curly braces that's going to get executed when you call the function by its name? Now let's go back to the playground and write a basic function. So I'm gonna start on the next line here, and I'm gonna use the cured F U N C space, followed by my function name. Now, for this one, I'm going to call it add two numbers because that's what we're gonna do inside that function. And I'm gonna put to parentheses like that, And next up, I would put to curly brackets. This is where I would specify the code that I want to run whenever I call. Add two numbers. So why don't we define some constants here? Let a equals one. Let B equals two on. I'll say, let C equals a plus B. So C equals three. And lastly, I'm going to print. See, I'm gonna run my code right here and let's come on playground. All right, so now it's run. But as you can see, there is no console output. And the reason why is because this code inside this function doesn't get executed until you call the function by its name. So the way you call it is you simply right the function name. And sometimes you can even use auto complete like that followed by the parentheses. And if we did define some sort of input parameter here that the function would require when you call that function, you would also have to specify that input data in this lesson for this basic function. We don't have to do that. All right, so let's run this line of code. And as you can see in the console, it outputs three as expected. Now let's try another one. So I am going to just get rid of that line there. So we're not calling the function, and I'll call this. Subtract two numbers. I'll say, Let D equals five e equals one and let f equals D minus E. Alright. And here I'm going to print and again, nothing is going to happen until I actually call the function right. So let's run the project now. And as you can see, there is four now. This might not be immediately obvious to you, but using functions is actually a huge time savings because often times when you write your code for your app, there are instances where you're gonna have to repeat a chunk of code in different places. Having duplicate code in your project is generally a bad practice and something that you want to avoid. And so, whenever you see yourself having to repeat code writing the same thing that you've written before in another place, then think about putting that chunk of code into a function so that you can call it from multiple places. Now there's one more tricky thing about functions that I want to mention to you, and that is the concept of variable scope. The idea is that any variables and constants that you define inside of your function, they only exist and can be used within the curly brackets of that function. So, for example, here in the add two numbers function, we have declared A B and C well outside of my function, that would be right here. I can't let's say, print a right that's gonna trigger an error use of unresolved identify. And that's just another way of saying that it can't find what a is. It doesn't know the same thing for B or C, and the reason for this is because we've declared a B and C inside that ah scope of that function. That's where it exists and likewise inside the subtract two numbers function we have DNF. I won't be able to access a, B or C here. Either try and print date. It still doesn't know what a is. We're going to get a crash. If for some reason you needed your variables to be able to be access outside of the functions, then you would have to declare these guys outside of the function. Now that's just something to keep in mind as you're starting to work with functions for a lot of beginners. They run into issues where they're frustrated with not being able to access these variables and Constance that they've declared inside their function. And now you know why. So just to recap, you learn about what functions are and how important they are because they allow us to organize our code into execute herbal blocks, which we can then call upon to perform specific tasks. You've learned how to define a simple function. You learn how to call that function so that you can execute the code inside of it. And furthermore, you learned about the variable scope inside of the function, and just to remind you about that if you declare variables or constants inside the curly brackets of your function. They're only going to be available inside that function. Now, in the next lesson, we're going to build upon what you've learned here and make functions even more powerful. Now click on over to the next lesson, and I'll talk to you over there. 9. 08 - Functions (Part 2): Hello. Welcome to my swift tutorial for beginners. Siri's now in the previous lesson, you learned about functions or what they are and how to call them. On this lesson. You're going to learn how to use them in an even more powerful weight, and that is to have your functions except data and return data back to you when you call them. All right, stay tude. So in the last lesson, we declared this function here to add two numbers, and when you call this function, it prints something down in the console. However, most of the times well, rather, sometimes we declare a function to take some input, perform a specific task and then return the result to us. So the first part of being able to do that is to specify that your function actually returns something back to you when you call it. And let's take a look at the syntax for how this works. So here's the syntax for a function that returns some data. You'll notice that we still have the funky word, and we still have the function name, followed by the parentheses. But after that you have a hyphen, followed by a greater than sign, which combines itself to look like an arrow followed by a space and then the data type of the data that you're going to return from the function. So if in our case, add two numbers, if we wanted to return the result to the function caller, we would probably put into where it says data type right here, because that is the type of the data that we are returning. All right, so after the data type, you have a space, and then you have the curly brackets again and you would specify your code. Now, if you do specify a return value like this inside your function, you must have the return key word in that return cured is used to actually end the function and return the data back to the color. So now let's jump back to our playground and modifier function to return the data to us. All right, so we've got our function up here, so we just add a hyphen greater than sign. And then we specify space, the data type that dysfunction returns. And as I've said we're working with in. So I'm going to return and into so right away You can see Exco detects hate. You're saying that this function returns data, but you're not using the return key word. And so we've got this error here. So let's modify our function instead of printing seat to the console. Why don't we try returning it? So we just put return space to see just like that? All right, so let's run our function now. Now nothing gets out. Put into the console where where the sea go, Right Well, what happens is that when you call a function that returns some data like we have in this case, you have to capture that data somehow. So remember variables and constants are used to keep track of data. Right? So all we need to do is say, let's define a constant Let's call it some. And we are going to assign to this new constant the result or the returned data from our function. Add two numbers. So let's run this and see what happens again. Actually, nothing will happen because we haven't out put anything into the console. But let me write this print statement here, so we're gonna print some and there's you can see there it is in the console. So what's happening here? We'll add. Two numbers were calling this function. It's declaring a B and then declaring See and adding a and B assigning it to see. And then it's returning. See, um, then we're assigning that result into a new constant called some. And finally, we are printing that into the console using this print statement. Now, it's not really interesting that whatever we call this function, it always just returns three. Right? So would it be cool if we were able to tell the function? Which two numbers that add? And we can do that by using input parameters. So let's take a look at the syntax for that. So, like I mentioned in, the last lesson we specify are parameters in between the rounded parentheses. Now, if you take a look at the screen, you're going to see how we specify one parameter for our function, and I know that's a lot of text, but we're going to jump into the playground, and I will show you an example. So you first start with the data type. Let's start from the right hand and work our way to the left we start with the data type of the parameter, and this merely specifies, you know, if it's an end. If it's a bull, you know what type of data are you asking for to be input into your function, right? And take note that there is a colon in front of that and then in front of the colon, you have your parameter name. Now you can specify any sort of name you want. Ah, you're going to be using this parameter name inside your function. If you want to access that data and then you have your argument label, notice that there is a space in between the argument label and parameter name. Now what's the argument label for? Well, it's optional, and it helps your function call read more like natural English. I'll show you what that means in a second. For now, why don't we jump back into the playground and take a look at how we specify this parameter ? All right, so let's modify our add two numbers function up here with the parameter and before I use descriptive labels, argument names of primary names, I am going to just put Argh here as argument label I'm gonna put space, and then I'm going to call this Pera for our parameters. Remember, Then we specify Colon, and then the data type of our parameter was just going to be it. The reason why I'm just specifying the argument label and the primary name as thes is because I want you to see what the resulting function called looks like. So down here, you can see exclude automatically detects that dysfunction call is no longer correct. In order to call the add two numbers function, you're now gonna have to specify that parameter. So an easy way to do that is just to delete this and then use auto complete again. And you can see here that now the function call has this which tells you the return type of the function. Now, if the function doesn't return any data, then you're going to see void in this column. It's that kind of like this down here. But our add two numbers function does return an end so easy and here and then you can see the parameter that it requires right here, along with the data type. All right, so let's double quick that or just press enter on that and you can see that the argument label is right there and then this interior, we can put a number in there. Let's put five. So now this is how you would call. Add two numbers with one parameter and you're basically passing in five into the function from inside of the function. Let's say that we wanted to assign that five into a We would use the parameter name. We're not using the argument label were using the prompter name inside the function here. So why don't we go print and the sum should be seven, right? You can see here now What if we wanted to specify another parameter so that we can also specify what beak should be inside of our function? While you can specify multiple parameters, you would just have to use comma in between each parameter. So let's take a look at that syntax. Now, as you can see, you have a comma and then you have your second argument label. Then you have your second parameter name and then the data type of that second parameter pretty straightforward. And you could repeat this for 3456 parameters whatever you need. All right. Now, let's jump back to the playground and specify another parameter for our function. So we're gonna go ahead right here and hit comma, and then I'm going to say are two pair of two, and that's gonna be an int. And now I'm going to assign Perrot to to be, and this function call will no longer be correct. So I'm just going to erase that and retyped it like that. And you can see now I have to specify to arguments or parameters, so I'm gonna say five and five. And the cool thing is that let me just go back there for a second is when you let's say you're specifying the parameters you hit five. You can press tab to jump to the next parameter. So that's a little shortcut. Little tip for you there. All right, so let's print to some, and we've got 10. Okay, Cool. So let me show you some other cool things. I did tell you that argument labels were optional, right? So why don't we go ahead and remove the argument labels here and just have the parameter name and the data type so incorrect argument labels. So why don't we get rid of that? And just now, when you make your function call, you have to specify still two parameters, right, because we still have two primers. But with the absence of the Argument label now it writes the parameter name. So let's go five and five that right? So generally, when you're specifying parameters into your function, you kind of want to be descriptive with them. So para and para to really doesn't mean anything, So why don't we change that to number one and number two and remember, changing these parameter names. It means that we also have to change this one number two, and as a result, this also changes. Oops. Okay, so we can specify 55 So that's all good so far. Now that you notice that initially when we had the argument labels, the function call was using the argument labels right. But now that we've removed the argument labels from this function definition, this has turned into the prender name. So if you had a need to make this read like more like natural English than you could specify argument labels to do it like that. So for example, I could say add two numbers and my first argument Lee label could be using and my second argument label can be end, and that would become function Call would be something like that Now, all right, add two numbers using five and five. So it reads clearly and it's really understandable. And inside your function, when you're working with your code, you still reference those parameters with the parameter name that was specified. You have number one and number two. Now, another trick that you could do. If you totally want to omit parameter names and labels from the function call and you just want to specify five and five, then what you can do is instead of using argument labels like this, you can just put an underscore in front of your primary made. There is a space in between that and your primer name, though, so if you specify the underscores like that, then you're function Call would look like this lips. Not that one, uh, numbers there Go now you just five and five and that now becomes your function call. So just to recap you learned about what return values are you learned how to use the return key word. You learned about what input parameters are and how to specify them. You learned about parameter names, and you learned about argument labels and how to omit them all together. Now I know it still might be confusing in your head, and that's why I highly recommend that you used exercises and challenges to practice more. Find all those resource is in the link in the description below. All right, now click on over to the next lesson. I'll see you there. 10. 09 - Classes: Hello and welcome to my swift tutorial, Siris for beginners. In this lesson, you're going to be introduced to classes, which is a highly critical part of the swift programming language. Now, I'm gonna warn you, it's a little bit of an abstract concept, but I'm sure you'll do. Fine. All right, let's get started. So in this playground here, I have several pieces of information. I've got three variables. Actually. Two of them are strings. One of them isn't into data type. Remember, back in Lesson two of this series, I talked to you about several common data types, and I just mentioned in a brief, like, one second sentence that you can create your own data types. Well, now we've arrived at that point. And what We're going to talk about our classes, and you think of it as a way to organize your information. Um, I know we talked about functions, and that was a way to kind of group pieces of code together. Well, when you think about classes, your mawr so thinking about information. So for example, in this scenario, I have a name. I have a salary and I have a role. Well, you can see where this is going. All of these different variables or pieces of information have to do with a person or an employee or something like that. So what we can do is weaken group this information together into our own new data type called employees. And in order to do that, we define a new class called employee. Let's take a look at the syntax involved. So you start with the class keyword followed by a space and then your class name. In this case, we would call it employees followed by space. And then you have a pair of curly brackets. Insider curly brackets is where you would define your class. Let's jump back to the playground in define our employees class. So you start with the class keyword followed by space, and then employees followed by space. And then we have our set of curly brackets. So in between those curly brackets, you would put all of the pieces of information that an employee would have. So why don't we take this information up here? I'm going to cut it, and I'm gonna pace that inside of our employees class. But one thing to keep in mind is that you're not defining the information for a single employee, because remember, we are creating a new data type here called employees. So this is a general definition that you can use over and over again. Instead, you're specifying what sort of information every employee should have, so we don't fill out the specifics Now. We just say that an employee data type should have a name. It should have a salary. We could start at zero and fill it in later. And let's say for roll it should be a string type of swell. And by just specifying two quotes with nothing in between them, it's just an empty string. So just like that, you've defined your new class, which is essentially a new data type. It's called employees, and every single employee is going to have a name, a salary and roll. Now here's the part that is going to get really tricky, and you really have to wrap your head around that, And that is that Your class that used to find right here is kind of like a template, so that that we've defined this class, how do we use it? Well, let me show you some examples with some previous data types that we've worked with before first. So let's say we have a equals 10 and let's say we have a B equals Ted. Uh, that will suffice. So what's happening here with this line? Essentially, we're creating a piece of data 10 right? It's gonna be stored in memory, and then we're creating a constant called A to keep track of that data in memory. Same thing happening right here. Ted is a piece of string data that we're creating in memory. And then we are creating a constant called beat to keep track of that data in memory. Now the same concept applies here with our new data type. We're going to create a new employees in memory, and then we are going to create a variable or constant called C. Let's say to keep track of that employees in memory. So let me show you how to create a new employees in memory. Well, all you have to do is write the class name, followed by two parentheses like that, and by writing this statement here we are creating a new employee data in memory. So why don't we create a new constant and assign it to that constant. Now, this employee data that you've created in memory is called an object also known as an instance of the class in this case, that is an instance of the employees class. So let me show you just tow drive home that this is your own custom type when you create a constant A. That would be that, you know, you're defining the data type of the constant right, And this would be that now A and B are really simple data types right into during stream. However, see is your custom type its employees and inside contains this sort of data here. And right now, it's all it's set to these default values. Would you have specified? But we can actually access that data inside of the employees and weaken set. And we can also get that data and the way we do that is using something called dot notation . So let me show you how it works. So down here, since we've created a new employee object and assigned it to see, um, let us change this the bar, actually, because we will probably be modifying it so we write C, which points to our employees object and we hit dot on our keyboard, and that lets us access all of that data inside of the employees. Plus, so we have name. We have role, we have integer. So why don't we set the salary to 1000 first? Yeah, let's do that. And I can show you print si dot salary and you can see that it's has 1000 right there. I can also set the other He says a data like that, you know, something like that. Now, another cool thing about defining your own data type using in class like that is that in addition to specifying what sorts of pieces of data is should have, you can also define functions in here. Yes, you can write f u N C space. Um, let's say do work. All right, you forget this is how you define a basic function here. And I'm just gonna print, uh, doing work or something like that. Um and then let's say because they are doing work, we are going to increase his salary by one. Doing work gets you noticed by your boss, which results could result in a promotion and you would get more salary. So that's at least my line of thinking right now. So let's say that that's the case. How would I execute this function if I just try to call the function, do work like this? It's not actually going to be recognized because this function is part of my employees class. I would actually have to call this function on an object of that class because I've created an employee object right here and assigned it to see I can actually do see using dot notation now. And you can see that I can access this function. Actually, one. We shouldn't change our Prince Damon here and insert the name Let's say for why would you refer to yourself in the third person doing work? How about Hi, My name is and I'm doing work. I don't think I'd hire someone like this who were first to something themselves like that, but let's see what happens. Okay. All right. It's running. Alright. Hi, My name is Tom, and I'm doing work. That's pretty cool. Now I want to show you something else. So I'm going to define another employee. I'm gonna create another employee object in memory. And I'm going to set this purpose name to Sarah. And let's say Sarah is okay. The same manager D dot salary he calls do without hope. This is an integer, and I am going to say d dot to do work. Now you'll notice that C and D are two separate employee objects. When I'm modifying the data for D, it doesn't affect sea and vice versa. And when I call the do work function on D, it has nothing to do with the do work function for C. So that's a basic introduction of how to use classes. So one last thing I want to mention is that when you declare a function inside of a class, it's actually called a method of that class. And these variables that you're defining inside your class are called properties of that class. And also I want to 0.1 thing out is that notice I can access salary from inside my function , and that is because it's declared up here. All right, so properties and methods, when they're inside classes now there's a lot more to classes. But I just wanted to introduce them to you in this video. I hope you can see why classes are a fundamental building block toe organizing your information. Now, in the next lesson, we're going to take classes even further. All right, let's click on over there and I'll see you in the next lesson. 11. 10 - Subclassing: Hello and welcome to my swift tutorial Siris for beginners. In this video, you're going to learn about inheritance, otherwise known as sub classing, which allows you to create a class which builds upon or extends from other classes, which have already been defined. Now this saves us a lot of time and effort from defining classes that do similar things. All right, so stay tuned. I don't know if you've noticed, but now that we've talked about functions, having the ability to organize your code into chunks on then classes, being able to organize and group variables and functions together in the way that makes sense, these are all different ways of organizing your code. Now today's topic subclass ing is another way to further organizer classes. So remember what I said about duplicated code and how it's a bad practice to have duplicate code all over your project, because that makes it hard to maintain and hard to manage hard to make changes. Now when I introduce functions, I told you that having duplicate code over your project is a bad practice, and it is, and functions were a way to address that. You can define a function and then you can call it from multiple places when you need to execute that piece of code. Classes are the same thing. Sometimes you might have to define two crosses, which are very similar. So instead of having to very similar definitions or classes, you can use sub costing and have one class extend from the other. So that's what subclass ing is all about. Let's take a look at an example. Using the playground that we had yesterday, we had to find an employee which had a name, salary and roll and a method called Do Work. Now remember these air called properties of the employee costs, and this is called a method of the employees class. Now let's say that I wanted to create another custom data type called Manager, right, so I would define a manager class like so right now, a manager also has a name, right so I can go ahead and to find that managers also have salary and rolls, and they also have they also do work. So, you know, I would just be defining the same thing very close to it all over again. Now, instead of doing that, what we can do is have the manager Class B, a subclass of the employee costs, so we can define that or weaken. Do that by putting a colon after manager and we can specify employees. And that is basically saying that the manager class inherits or is a sub cost of the employee costs. And this also means that the manager class automatically inherits all of the properties and methods of the employees closet. So let me demonstrate for you. Let's say Let em equals issues bar and equals a new manager object. So I've just created a new manager piece of data in memory and assigned it to em. I can say you can see here, Maggie. Maybe he's got a bigger salary role of manager of tea or something like that, right? And M can do work. So Hi, my name is Maggie and I'm doing work now. Let's say, as a manager, you also want to keep track of the size of the team that the manager and is managing. So for the manager class, we could have another property called team size, you know, and we can start that at zero. But now for my manager object down here. In addition, toe all of these properties and methods that it inherited from the employee costs. In addition to that, it also has, you know, the properties that I have defined inside the manager class. So I can say the team sizes 10. Essentially, I was able to create a new class based off of an old class right, and add additional functionality to it. Now, you can also modify existing functionality. So let's say that you know, when a manager does work, it's he or she is not just doing work here. She is managing people. So what we can do If we wanted to change the definition of do work, we can say we can redefine it here after using this keyword override. So I'm gonna override the do work method, and I am going to print. I'm managing people very important, right? And a salary increase. Wow. It's gonna increase by two. All right, so now when I run this, it's not going to say hi. My name is Maggie. Dumb. Do work. It's going to take this overridden function, right? Because M is a manager. So that's why we get down here. I'm managing people. But did you know that if you wanted to, instead of replacing the functionality of that inherited do work method, you? Let's say you just wanted to increase the functionality you wanted to add to it. So what you can do inside here after overriding it, you can call the do work method of the employee costs from here. All you have to do is write super dot. You can access these properties, or you can call the do work method. So now when I write m dot do work what, it's actually going to do it. It's going to execute the do work method definition from the employee class. And then after that, it's going to do this additional code that I've written here. So let's run our project and see what that looks like. You see? Hi, my name is Maggie, and I'm doing work and I'm managing people. The reason why this keyword is called Super is because the class that you're subclass ing from is also known as the super class or the parent class. So for the manager, cost employees would be the supercross or the parent class, and that's why the keyword is called Super. All right. So in addition to being able to redefine the methods of the Supercross, I can also declare new methods. So I can say, you know, fire people. Oops. Uh, what's going on? I'm firing people. So now I can say m dot fire people. But, you know, if I let's say, declare a new employee here just to demonstrate using dot notation on the employee object, you can see I only have those things which have been defined in the employee costs. So that's how powerful subclass Incan be. It can really save you a lot of work. You're not gonna have to redefine. Two different things of that are very similar. What we've got right here is actually one level of sub classing or one level of inheritance . But it can actually go much deeper than that. For example, an employee is also a person right, and all people have names. So I could, for example, declare another class up here which contains the name property, because all people have name and you know so then inside the employee class, I wouldn't have to define that. And instead I can go that the employee is a subclass of person, right? So you can build these hierarchies in these trees, and it's really a way of organizing your data and your information. Inside of your classes. You're organizing your properties and your functions. So now you can see holistically how all of these things are starting to come together. Variables, functions and classes. Okay, so this was a simplified example of sub classing, but it's essentially how it works. And it's very predominant in the swift programming language, as you're going to see in the next lesson. As you can see subclass and helps you save a lot of time by allowing you to define your new classes based on what already exists, and then improving upon that or customizing it a little bit without having to redefine everything all over again. And now you know the drill. Let's click on over the next lesson and I'll see you there 12. 11 - UIKit: Hello and welcome to my swift tutorial for beginners in this video. I want to introduce you to you I kit, which is an Apple framework that contains a lot of the classes we're going to need in order to construct Iowa's abs. All right, so let's dive in and see what's available, and you like it. So if you imagine most APs, there are common elements between all of them, such as labels, buttons, maybe text fields, images. And if we were to build each of these components from scratch every single time we built a nap, it would be very time consuming. End a lot of wasted effort. And so Apple has provided us a library of all of these pre built elements that we can use in our laps, and they've called this library. You like it? That's what we're here to discuss. Now you like. It contains a lot of user interface elements, and I know it strays a little bit away from swift programming, which is what this syriza about. But one of the very interesting things about you I kid, which is relevant to what we've been talking about, is how they use inheritance and sub crossing to create all of these different you I kid classes, so I'm gonna go through that with you as well. But first, let's take a look at where you can see the documentation for you like it. So if you just type into Google Apple space, you I kid into a search, it should be the first result. When you click on that, you're going to get to the reference page or the documentation page for that, and you scroll down and you can see all of the different things in you. I kid, you can see it doesn't just contain user interface elements, but it contains other things, like causes for animation, touches, gestures, dragon job and stuff like that. Another really handy way to explore you like it, which I recommend even more, is just to open up X code. If you go under window, you should see developer documentation, and that's what you want to click and bring up on the left hand side. Under Swift, you're going to find you like it near the top, and it's much easier to browse this like that. One of things that they have removed is kind of a hierarchy that shows you how each of the classes are sub classes of other classes above it. And so I wanted to pull up that diagram for you to illustrate how they're using inheritance and some classing. And so I Googled it, and I found an old image from back then that shows you how each of the elements derived from other elements and all the way here on the right hand side, you're going to see this. You I button here, and this is your classic or standard I west button that you have put in your view. But notice if you follow the lines that it's a subclass of you I control, which is a subclass of you, I view, which is a subclass of you. I respond er, which is ultimately a subclass of Ennis object. So it's very interesting this seat. If you are curious about what any of these classes do, you can go into this documentation, which I showed you here. Let's say we go under button. Great. You can see the declaration here, class you, I bun, that it's sub classes from you I control, just like we saw over there in that, Harkey. But if you click that you I control, it's gonna bring you to that class and you can read about it. Is you can see it's the base class for controls, which are visual elements that convey a specific action in response to user interactions. Pretty cool. But down here, you can see that you I control, is actually a subclass of your view. So you click on you, have you and see what that does. It is basically something that you can put on the screen for the user to see. Now you, I view, is actually a subclass of you. I respond. Er, what's that Click into? There is an abstract interface for responding to and handling events, which explains why so many user interface elements are ultimately a subclass of US responders. But you I respond. Er itself is a subclass of Ennis object. So what's that? Click on that, the root class of most objective C class har keys, and we're gonna talk about that in a second. Why that says objective seat from which sub classes inherit a basic interface to the runtime system and the ability to behave as objects. So It's basically what makes an object tick, if you will. And the reason it say's objective. C is that originally before Swift, the language to build APS was objective C So a lot of you, like it is actually still written an objective C with swift being a layer on top where you can use these crosses as swift. One of the dead giveaways is this n s prefix in front of the class name. Usually when you see that you can expect that that is an objective C class. However, whether that's objective, sear swift. That's not what I wanted to point out to you in this lesson right here. What I wanted to show you was eight. How Apple has created this whole. You like it library from all of this inheritance and sub classing. And that's really cool to see how they organized all of the different pieces there. And then be to let you know that there is this you like it library at your disposal with so many pre built components that you can use to build your out. Now, once you finish this swift programming Siri's and you move on to learning about X code and building user interfaces and stuff like that. All of these classes are gonna come in handy. All right, so at this point, that's all you need to know about the U I. Kid library. I'll see you guys in the next lesson. 13. 12 - Initializers: Hello and welcome to my swift tutorial Siris for beginners. In this video, I want to talk to you about initial Isar methods for classes. These guys exist to make sure that when you create a new object of your class that that object is ready to go. Plus, you can customize these initial Isar methods to set up your object in any way that you want when you create a new object from your class. All right, so let's get started and see what that all means. So what I've got here on the screen is the playground that we created back in the classes, part to lessen. When we're talking about some classic just to remind you, we have a person class and then we have an employee class which is a subclass of that person class. And then we have a manager class which is a subclass of the employees class. So now have jog your memory about what we have here. Why don't we create a new person object? Do you remember how to do that? First of all, you use the class name followed by two around in parentheses. Right? Let me show you. Let's do it here. Person. Two random pregnancies. And just like that, we've created a new person object. Well, what you might notice is that this kind of looks like a function call, right. Remember to call the function. You write the function name followed by two rounded presidencies and any input parameters in between those pregnancies. In this case, right here, person with these two around pregnancies, you actually are calling a function of that class. Now, I know that might seem weird, because if you scroll up to the top here, we don't have any functions that cleared in the person class, right? Well, there's actually a initialize er function that is default to all classes that you don't have to declare and let me show you what it looks like because you can explicitly declare it. So if we were to explicitly declare the initial Isar function of the person class, it would be using the key word in it, followed by two rounded brackets, followed by thes curly brackets. And you can put any sort of initialization code can hear. It's a custom in it code. I also noticed that for this special initialize er function, you do not need the f u and C keyword that we normally used to declare functions. This is an initial Isar function. So let's say, for example, I put in here that I want the name property to be joke right? And now, if I create a new personal object, say, Let my person equals new person object what's actually happening here when I call this? It is creating a new personal objective, but it's using this innit function here, right? And it's actually setting. This is running this custom coat. So to prove it to you, why don't we print out the name right after creating that object so you can see here it says Joe as the name. Now the initial Isar function is useful for you to put any custom code you want in narrative. Set up the object. If you don't specify and an it function at all like what we had before then it's still there. You can still create new objects from that class, and that's actually what the purpose of the initial Isar function is for. It's too set up a new object of that class, you know, allocated memory, do whatever it needs to do to return that object to you. Ready to use? Now here's the interesting thing about initialize er functions so we can have our basic one . But we can also have different ones which accept parameters. For example let me show you this We can accept the parameter called name. Let's make it a string like that. And then we can also have our basic one that we have before like that so we can have multiple initialize er functions. Let's go back down here now I can create a person object with the basic initialize er function which doesn't do anything. And when I run this code, it doesn't print anything out because I haven't written anything in that innit function. However, don't forget that I created another one which accepts a name. So this time I could put in a name like that if I print it not doing anything right now, Did I? I don't that I do. Oh, yeah, my bad. I didn't do anything in here. So what I wanted to do inside this initial Isar function was to set the name property to the name input parameter that got passed in here now I could write something like this where I'm trying to set this property right to the name that gets Paston. But as you can see, it's a little bit ambiguous. X Code is telling you that there's an error, but it's not recognizing that I'm trying to set this property. It thinks I'm trying to set this parameter to that parameter. So what you can do in this case to resolve this ambiguity is to you use the self keyword so you can write something like that self dot name. And when you do this, this is referring to that objects name eso. This is basically referring to this property here and now This name is from this prender. So it's very clear what you're trying to do here. All right, so let's run this code again and you can see that this time it prints Tom. So let me ask you another question. Since the employee cloth subclass is the person clause, that means that the employee class also inherits all of its functions from the person class , right? Do you think that this employee class also has these in it functions? Why don't we give it a try. Go back down here, Let my employees equals employees. And as you can see, the employee class does have this innit function that it inherited from the person class. So I can use this with the employee class as well. So that's pretty cool. Now I want to talk about overriding in it functions, you know, just like how we talked about right here, where the manager class overrides the do work function of the employees class. And then it calls Super dot do work, which is going to execute the employees do work function as well as you know, any code down here. The same thing applies for in it functions. So let's say that we have in the person class we have this an IT function right where you pass in the name, Let's say, for the employees class, I wanted to do something extra. I wanted to override in it. So we're gonna override the same function from the person class, were overriding this guy right here. I also want to initialize the role, so I'm gonna do self roll. Let's default everyone to analysts or something like that. Everyone starts off at the analyst level However, what I can do is call this person's or sorry. I called the super classes in it function and pass the name into their. So this this is calling in the in it function of the person class. This is additional net code. All right, So now by calling this in it where I pass in the name of the employees, like if I print my employees dot role, my employees name so you can see that it's set toe analysts and then set to Joe here. So what I wanted to demonstrate here was that even within it functions, you can use the over I keyword and provide a custom implementation of that initial Isar function and then also called the Super Classes implementation as well. So I hope that was clear. If it's not, just leave a common below, and I'll be happy to clarify things for you. All right. Later on, we'll dive a little deeper into initialize her methods, and we'll talk about how they're two different types, one called designated and one called convenience. Initialize Ear's. All right. Now click on over to the next lesson and we'll talk there 14. 13 - Optionals: Hello and welcome to my swift tutorial for beginners in this video. I want to tell you all about optionals, which are probably one of the most confusing topics for beginners. If you've ever looked at swift code and come across exclamation marks or question marks, then you've come across optionals. So let's get started and find out what they're all about. So to demonstrate what an optional is, let's first take a look at how we've been declaring our variables and constants. As you remember, whenever we declare a variable used far and then we use some sort of name, let's just say a for this example. And up until this point, you've always seen me assigned something into my variable declaration something like this for whether I declare, you know, a string. I'm always assigning a piece of data into my variable declaration or constant declaration right away. Now there will be instances when you're building APS that you may not want to assign data to your variable right away. You might just want to declare it, but if we try to do that, let's erase this assignment statement and erase the data as well and just leave it at that . You'll see that X Code really doesn't like that. And that's because it wants to make sure that all of your variables and constants actually are keeping track of some sort of data, because that's the purpose of their variable in the constant right. While using optionals, you can create a situation where you declare a variable or constant without assigning something to it first, in which case it is empty. So how do you define emptiness? Well, there's actually a type for empty, and it's called nil, and it's simply a keyword like that, n I l which stands for empty or nothing. Now, if we don't want to assign actual data toe are variable First, we can assign it No like that, right? And that means that that variable contains nothing. However, as you can see, we're still having some problems here. Remember, I told you about data types for variables and how variables can only store data of a certain data type, and you can explicitly state the data type of that variable. And if you don't, then it's going to take on the data type of the first piece of data that you assigned to it . So, for example, for a If I did that, then it would take the data type of my integer, and it would determine that a should have the data type of int. In the case of nil, however, there is no data type for empty, and so variable A really doesn't have a data type right now, and we have to give our variable a data type. So in this case, if you're going to assign empty into your valuable, that means you don't want to put any data into it. Yet we have to explicitly put a data type. Now let's go ahead and put int right. And for this one, let's put string like that. Let's run it. As you can see, there is still a problem because the into data type doesn't include empty. In fact, none of the data types include nil as a valid value. Neil is not a valid integer, and nil is also not a valid string. So that's why we can't assign nil to an integer variable. And we can't assign Noto a string variable. Well, this is where optionals come in by adding a question mark to the data type like this, this becomes an optional integer, which means that it could either be an integer or it could be no Same thing goes for this right here. The data type is now It's not string. It's an optional string, which means that it could contain a string object or and might contain? No. So that's the gist of an optional. In order to demonstrate how toe work with optionals, I'm going to use another example. So let me delete this for now, and then let me grab a piece of code that I prepared for you. Let me just run the project here and make sure that it runs. As you can see here I have a class called Christmas present, and this class contains a function called Surprise, which returns an integer. Now, this integer is going to be a random number from 1 to 10. So why don't we just use this code here? Uh, let's use Let present equals. Let's create a new Christmas present object using that. Remember Initialize er functions, right? And then we want to activate the surprise. So sorry. Present. Don't surprise. And then we're gonna print the output of that function. So let's run our code when we get five in our console right here. So that's the surprise. Now, this data type of this constant right here, if I explicitly declare it would be the type of my class, right? Next, Why don't we make this an optional type by adding the question mark there? And then let's say that we put nil in there. You can see here that there is an error. Expert says that the value of optional type Christmas president must be unwrapped to refer to the member, think of member as function or property, uh, must be unwrapped to refer to the function Surprise, right? And the reason for this is because I told you, with an optional data type, this constant could contain a Christmas present object, or it could contain mill, and in this case, we do know that it contains milk. So what that means is that you have to check that optional constant or optional variable to see if it actually contains an object or if it contains nil before you access any of its functions or properties. Because you can't call the function on empty great, you can access a property of nil. So what we have to do in this case is just double check that the constant present actually contains an object, a Christmas present object to be specific before we call the surprise function on it. Now there are several ways of checking an optional type to see if it's nil before using it now demonstrates some of them. Let me erase this line first, so we're going to check the optional to see if an object exists or if it contains an object . Say it like that. So first thing we can do is basically compare it to nil with an if statement. So if present is equal to milk, if this is true, then it contains no, so don't do anything with it. Els. It contains an object right now. The reverse of this is also true. You can check if present not equal to milk. All right, then, if it's not equal to know that it contains an object. So why don't we use this statement here? Because we want to only call the surprise function if there is an object and we don't really need to do anything with it. If it is a nil. So why don't we erase this one here and let's use this one so it contains an object. Now call the surprise function now, since I have already checked that it contains an object I should be able to just call Surprise, right? You'll notice that X Code has helped us put this question mark here because that's what it thinks you want to do. But I'm going to erase it because I want to demonstrate something for you. See, if I try to run this, there's an error, because you see with an optional variable or an optional constant before you can actually access the value inside that optional data type. Whether that's a natural object or whether that's no, you have to unwrap that optional. Now I know that's a weird term, but a good analogy or a good metaphor to think about an optional variable is that it's like a Christmas present or it's like a box and you don't know what's inside of it. It could actually contain an object, or it could be note, but you're never going to know unless you unwrap it. First, you open that box to see what's inside now? Right here, you might say, Hey, we've already checked that. It's not nil, right? So this check is kind of like taking that box and just shaking it and listening to it. You know, when you're a kid trying to find out what's inside your present, that's what that's like. And all that does is that it tells you if there's something inside. I mean, if it's nil, you're shaking it. This it's gonna not gonna sound like anything. But if there's an actual object inside and you shake it, you'll hear something. So this check right here lets you know that there is something inside. But that doesn't mean that you can access what's inside right until you unwrap it. So let me show you how you can unwrap that variable and get at the object so that you can call the surprise function on it all you have to do to unwrap this optional variable is used the exclamation mark after it, and what that does, is it tears? Open that box and you get whatever's inside, whether that is the actual Christmas present object or where the note. So because we've already checked here that it is an object I'm going to say dot surprise and I can print that, right? So let's run the statement here. Actually, nothing is going to run. Do you know why? Because it's actually knelt, right? So our if statement actually worked. So this if statement said, If it's not nil right, then unwrap it and then call the surprise function on it. But since it is nil didn't do anything. So why don't we change the statement? Why don't we actually put a present inside the box? So now when we run it, we're going to get the random number surprise, which is six. So now you know how optionals work. But I mentioned there are a couple of different ways of checking right to see if there's an object inside of your optional. So this is one way another way is called optional binding, and this is a little bit more advanced than that basic check there, and it's kind of another way of writing. And if statement, you say if let the actual present people's president, then we will print actual present dot surprise. So let me explain this statement right here. It's still an if statement. So you're checking something you're actually checking to see if present this optional variable to see if it's nil or not. If it is nil, then it's just going to pass through this if statement and not execute this stuff inside. However, if this optional variable does contain an actual object, then it's going toe. Assign it to this constant that you're creating right here called actual present. So it's almost like two statements in one the if statement checks to see if it's nil. If it's not nil, then you're gonna assign the actual object unwrapped into actual present this constant, and then you can. Inside that estimate, you can use actual present as the actual object, because what it will do is that it's going to take the unwrap object and assign it to actual president. Okay, so you don't have to do any unwrapping here, and he could just call surprise. So you'll see six and 44 was from here, and six was from here. All right. Last thing to show you about optionals is another thing called optional chaining. Now, this is what you saw a little earlier when X code tried to put a question mark there, so let me show you what that is. So you put a question mark next to the optional variable and then you call your method like that. So with optional chaining, you can see we don't have any if statements or anything like that. But basically what this does, is it checks to see if this is gonna be nil or if it actually is an object? If this is Nell, nothing happens. You're not gonna call that function. However, if there is actually an object in there, then it's going to call the next part on that object. So in this case, it's gonna call the surprise function on the actual object because there is an object in that optional. So that's what's known as optional chaining. So why do we even have optionals and swift? Well, the reason is because Swift is a type safe language. And what this basically means is that Swift forces you the programmer to be very specific about the types of data that you're working with in your code and in the long run, this actually helps you because it forces you to think about things thoroughly. Such as if this variable will need to contain nil or if it's always gonna have a value. And also how were restricted to certain data type for variable, where you're not gonna accidentally assign another data type to that variable because it is type safe. So I just wanted to revisit some of the ways of declaring our variables and constants with optionals now, because there's one thing that I haven't shown you yet and that's what I'm gonna show you now. So in here, lying three, you see kind of the standard way where we declare a variable with the type and then we assigned data to it. And you've also seen about how you can add the question mark after the data. Type to turn that into an optional type and you can assign nil into it. Well, you can also just do this, And that's absolutely fine, because when you declare an optional data type like this for variable C by default, it's going to be no. So you don't actually have toe explicitly assigned mill to it. So when you're declaring optionals, I would recommend that you do it this way. There is also another type of optional that you can declare and that is using the exclamation work. Now I know in this lesson I showed you that putting in exclamation mark is unwrapping that variable or constant to see what's inside the optional. Right? Well, this is called an unwrapped optional. So this allows you to de Ken store a string for nil, but it is already unwrapped, so you don't have to unwrap it. But it can also store nil see, construe or a string or nil. But it is wrapped, so you have to unwrap it in order to see the contents, whether it's nil or actual strength. So when would you want to use this sort of optional versus this one? Well, I would say in general you would want to use this one because it provides that sort of type safety checking that X code has. So when you try to use, see in some weird way and you're not checking against the nil, X code is gonna warn you. Hey, this is an optional, so you might have to check for nil before using it. You might not be able to call this property or this method on C because it might be empty. So it provides you, um, all of those warnings, which makes you a better programmer, and it makes your code more robust than will probably crash less so if you use this instead , you can also store nil or values in here, so it gives you that flexibility. But it's not gonna have any of that type safety checking. So X Code is just going to assume that you know what you're doing. It's not gonna warn you that it might be nil because it's already unwrapped, right? But just know that D may contain no. So it's It's almost like you are driving without a seatbelt. Maybe that's about example. But because there are places where you might want to use this, you know for sure that Onley initially it may be no. But then, after a certain point, you can always be sure that there's a value. Then maybe it's safe to use that, and then you can ignore all of that sort of optional binding optional chaining all of those checking for nil. You can save all of that coat, however, if it's a variable which may contain the value in the nil, and then that value might get erased. So it's nil again, and it keeps flipping back and forth. That may be having it as this sort of optional is better, because then it forces you to remember to do that checking. So I just wanted to give one more quick example about thes two kinds of optionals using our Christmas present class. So why don't we declare a new Christmas present? Like So let's say present one is equal to Well, let's declare the type of this. So we're going to declare a new Christmas president optional like, So we're gonna sign it, Neil. Right? And they were born to do Christmas present to, and we're going to use this and remember, we don't actually have to assign it to know, but I'm going to write it anyways, just so it's very clear to you what's inside these variables right here. So if I wanted to, let's say, do president one dot Surprised like that, let's remove the optional chaining. You know, we get that sort of type safety, checking it, saying that it's an optional. It might be nil if it's Nilda and you can call surprise on it, so make sure you, you know, you do some sort of checking. However, if I do present to dot surprise, you can see that. Let me just show you any. Type it out. You can see when I do that, there's no sort of. There's no optional chaining there. There's no you don't have to unwrap it at all or anything like that. It just treats it as an unwrapped optional. You could just use it as is, and you're not going to get any sort of warning. So I'm gonna run this. But now you get an actual app crash. Uh, so you know, if this goes unchecked and you launch your app and the user is using it, then you're actually get going to get an app crash, which is really bad. Whereas if you did it with this sort of optional, you know, even as you're running it, you're going to get a warning from X code, forcing you to fix that and address that before actually shipping your app or even allowing you to run your code. So, like all the other things we're learning about, Swift, we can go deeper. There are additional things that you can learn about optionals, but this is your introduction, and I just wanted to tell you what they are in a little bit about how to use them. Practically speaking, you'll be using them most of the time. Like how we covered in this lesson in the future will cover more of the complex aspects of optionals. Also, you might be wondering why and when we would use optionals. But let me tell you, you will definitely come across optionals when you're building APS. And when we get to building our acts together now you'll know what they are and how they're used. Because you've watched this lesson. All right, Click on over there for the next lesson and I'll see you there. 15. 14 - Properties: Hello and welcome to my swift tutorial. Beginner Siris. In this video, we're going to talk about properties which you have been using already ever since we introduced them in our classes lesson. However, in this video, I'm going to go through some additional things that you can do with properties. All right, so let's get started. So before we start, one thing that I wanted to point out to you, just in case you didn't notice is about property scope. So remember back when we talked about functions and talked about variable scope and how if you declare a variable inside of a function, you're not gonna be able to access and use that variable or constant outside of that function, you can only use it within that the curly brackets of that function. So each function has its own variable scope. But when you declare a class like we have, for example, here, these properties that we declare up here, they're kind of just like variables that are at the class level. So because they are declared up here at the class level, they are accessible and usable by any of the functions inside that class. So for example, here you can see our do work, function or method. Sorry. If a function is inside of a class, it's called a method, Remember? So in our do work method of the employees cause here we can access the salary property because they declared up here and if we had more methods in this class, inside each of them, we would be able to access the salary or the role. All right, so that's just one thing I wanted to get out of the way in case that wasn't clear. One cool thing that I want to talk to you about declaring these properties up here is that aside from them just being variables at the class level, there are some unique things that you can do with them. For example, let's take this manager class right here. Let's say that we wanted to create a bonus property that would basically determine how much of a year end bonus this manager would receive a za part of their compensation. So let's create a new property called bonus. However, on this is going to be an int type. However, the bonuses actually tied to how many people they manage, so you could do something like this, for example, may be in the initial Isar function of the manager Kloss. You could say that the bonus property equals, let's say, team size times 1000. So you get an extra $1000 for each team member that you manage, right? So you could definitely calculate that in the initial Isar function of the manager and set that property. However, there is something called computed properties and that allows you basically to make your property a calculation. So instead of having to explicitly assign 1000 times team size to the bonus property, you could just make this bonus property a computed property. So to do that, you would declare your property and you have to specify a data type, and then you have your curly brackets. Let me just write a comment here. This is a computed property. When it's access the code in here run, then we'll return value. So here we can say return team size times 1000 and literally as simple as that. So the bonus property is calculated via this calculation here. The problem right now is that the team sizes zero, so we need to be able to specify the team size. Why don't we set that as part of the initial Isar function? So we could We don't have the over I Let's create our own one, which takes in a name. But it also takes in a team size, which will be an integer, right? So this is our own custom initialize er function for the manager class. However, because the manager class is a subclass of employees and it inherits all of the employees, classes, methods and properties, we have to make sure that all of those are initialized properly, too. So the way we do that, we can simply call Super in it, which is basically calling the unit function of the employees class. So we're gonna pass in the name this calls in it of the employees class additional. Can it work here? We will set self taught team size people's team and because you know the parameter is a different name from the property, we technically don't need the self. We could just do that, and it's very clear what we're trying to do, but it doesn't hurt to add the self as well. Just be consistent in your coding. All right, so now let's try to create a new manager object and then try to access this bonus property . So down here, let em equals Manager. We're gonna use our new fancy innit method. Let's call her Kate and the team sizes. Let's say 11. All right, let's print out. What would her bonus be? Let's run this code and it is 11,000. So that's pretty cool. Now there are additional things that we haven't covered in this lesson, such as getters and centers and property observers. But we'll have to do another lesson on properties later on. For now, this is a great start. Now click on over to the next lesson, and we'll talk over there. 16. 15 - Designated & Convenience Initializers: Hello and welcome to my swift tutorial Siris for beginners. In this video, we're going to revisit initialize her methods. And I'm going to tell you about designated versus convenience initialize er's. So let's get started. So here I've got a person class and all it has is one property called name, which is initialized to the string. None. Remember when we talked about classes and default? Initialize Ear's All classes will have a default, innit? Initialize er starts why I can create a new personal object like this. It's actually calling the default initialize er now I told you that the purpose of the initial Isar method was to make sure that that object is set up and ready to go. Now, in addition to allocating memory and doing all of the other things that it needs to do to create that object and return it to us, another job of the initial Isar method is to make sure that all the properties of that object are initialized. And let me show you what that means right now. So, for example, in this person costs, I have a name property. It's initialized with this piece of data, none now Let's say I create an optional let's say not salary. Let's say, uh, net worth or something like that. Um, and let's make this an optional integer and that is also already initialized to know because, remember, I told you that by default, the value is nil for optionals. Now I can also say gender. Let's make this an optional string that is already unwrapped. Now this is also initialized to know. So right now, by default, all of the properties of the person class are already initialized. So that's why I can create a person object like that without a problem. But let's say that one of the properties is not initialized. Now let me show you what that looks like. For example, for name, I can say that it's gonna be a string type, but I can not a sign in any value. Right? Then it's going to start to complain and say that hate your person. Class needs to have an initial Isar explicitly where you initialize the name property. So in this case, what we do is we doing it, and then we assign of value to that property, right, because this is not an optional right. If it is an optional and that's a different story, it is initialized to know. But when you just say that it's a name property and it should contain a value, right, this is the string data type of should contain a string value and you're not assigning a value to it. Then it falls on the initial Isar method to give it value before that object gets passed back to you. When you create a new person object so I can show you that's they let a equals new person object. Then I can print a dot name. I can show you what that is. Alright, it's none because when we create this new person object, it's calling this initialize er, and it's initializing this name property to none. You can also try to print a net worth for you and you'll see that it's gonna be no. Now these initial Isar methods which ensure that all of the properties are initialized, you know, we're just calling them initialize or methods. But the proper name is designated initialize er and these designated initialize. Her methods can be guaranteed. Teoh, return that object to you, ready to use all of its properties initialized so on and so forth. Now there's another type of initial Isar method called a convenience initialize er. So these convenience and initialize er methods are for you to kind of pre set some of the properties of that object based on what you need. And then that convenience initialize er should call a designated initialize er just to make sure that all of its properties air set. So let me give you an example of what? That what that looks like. So let's say that this is our designated initialized, right? Because because it makes sure that all properties are initialized and it's ready to go now . I can create a convenience initialize er by using the convenience keyword like that. And let's say I want to create an initial Isar to create a rich female. So let's say that you need to pass in the gender and you need to pass in the net worth or escribio a rich person in general, right? Then I would First of all, I would need to call the in it right called the designated initialize er Teoh ensure that the object is ready to go set any other properties or custom code to initialize for this scenario. So I can say, you know, self dot gender is equal to whatever gender was costed himself thought net worth is equal to. I forgot to put a type here, So let's say that end Missing self, right? All right, So this is creating a new person object, creating a new rich person, object b equals person. And I can use my, uh, male. Let's change that to mail stuff. Right? So this is convenience initialize er just gives me an easy way to create a specific type of person object initialized to some sort of whatever values that I need, but it calls the designated one because this is kind of like the steadfast anchor initialize er that makes sure that all of its properties are initialized, so you can count on it as sort of like the go to initialize er. So just to recap designated initialize er's are those that guarantee all of its properties are gonna be initialized and that that object is ready to go for you, whereas convenience initialize er's are optional and they basically give you an opportunity to create an object. But preset it to the values that you need. Like what we did in this case. But convenience initialize er's must call a designated initialize er ous. Well, just to make sure that everything is set up and ready to go so you can see that we did it here in line 16. So that's the difference between a designated versus a convenience, initialized her method. All right, click on over there for the next video, and I'll see you there. 17. 16 - Arrays: Hello, one. Welcome to my swift tutorial, Siris for beginners. Today you're going to learn how to manage a collection of data in what's called an array. If you're working with many pieces of data, it's going to be hard to manage them all, using just constants and variables. So let's take a look at how rays can make our life easier. All right, stay tuned. So Swift has a couple of collection types that you can use to manage your data easily, and the one we're going to talk about right now is called an array. And this is a collection type that is ordered by indexes. And that means that there is a specific order to this list of values. So you can see here in this demonstration or this example it starts at zero. And then it goes 1234 and so on and so forth, and at each position there is a value or a piece of data. So there is a defined order, and that's really important to know. Let's jump into the playground where I can demonstrate and need and an example of how to use a race. So right here I've got three variables A, B and C And let's say that I wanted to change these strings to my dog, my cat and my bird. Well, I can go about it this way and say something like this. I can just add the word mine with a space to a right. So a is dog. I'm gonna add my in front of it and re assign it to eight. So that would be my dog. So I could repeat this with B and C. But I mean, this is only an example. With three items, let's say we had 100 or 200 items then that would be very, very tedious, right? What I could do is also I can put these values into an array, and what that looks like is it starts with a pair of square brackets, and each item in the array is separated by a comma, so I would have dog comma, cat comma and then bird, so there's no comma at the end. It's only in between the actual items, So this is an array of three items, with dogs starting at Index zero, cat at the next one and bird at next to. So just like what we saw here, a dog cat bird. That is our rate. So having this array is great, but we need some sort of way to reference the items in the array. So why don't we assign this a rate to a constant called Maya rape? And in order to access these items, all I have to do is, say, my array and then use my square brackets and then put in the index of the value that I want . So if I want a dog, I would put in index zero. So it's print that and we could see dog. If I wanted Bird, I would put in index to right because it started at zero. All right, so in that case, I could do something like this. My array zero is equal to my space. My array zero kind of mirrors. This statement, right. This shows you that you can use this sort of same syntax. Uh, and there's actually an error here. This is a really great example, because I'm trying to assign something into my array at in next zero. But this is a constant, so I can't modify it after it's a sign, so I actually need to do variable like that. It's make my array a variable. All right, so this is great because it shows you that this syntax is to retrieve the item at index zero. But I can also assign things into index zero using this assignment operator like that. Right? So the resulting value at index zero is you guess that my dog, right? But this isn't very efficient either. I mean, I'd have to write this line three times or however many times, for however many pets I have. So this is where it gets really powerful because you can use loops. We learned way back then in conjunction with a race. So let me show you how that works. So, for example, let's use a for loop or a for in loop. I mean, let's say there's a counter in 0 to 2, right? So now I can say, uh, well, why don't we just print it out for now so we can print out my array and then it's access the index I can put encounter in there. So let's see what that looks like. If I run this code Seo print out my dog, Canton Bird. But actually it's because this line modified what was at in next zero. So let me get rid of that line and let me print this again. She can see Dog, Cat and bird. It's merely printing out each index of that right? But already this is really powerful, right? Because we have one line of code and it's being looped three times. But each time it loops, it's doing something different. What if we did something like this? What if we did? My array counter is equal to my right space, plus my array counter. Right now we're talking because what we're doing here is each iteration of the loop. We are accessing that index and then we are adding my in front of it, and then we're reassigning it to that same index, basically changing the value, and then we're printing it out here. So if I had 200 items in my array, I would just change this to 1 99 right? And that's very little code compared to what we were doing up here, right? So you can start to see how powerful it is to use a raise with loops now. What if we didn't know the range of the A rape? Right Right here. I'm assuming that I know there are three items in here. That's why I'm doing this range 0 to 2. Well, the array comes with some handy properties that we can use. One of them is called Count, which returns. How many items are in the A rate? It always starts at zero. So we're going to start at zero if we want to access the first item in the rate. However, we are, actually we can use the account property of their right so we can do my array dot count. But they're going to run into a problem with this. Let me show you why. So if I run this code, you're going to get my dog, my cat, my bird, and then index out of range. Whenever you see this error index out of range, you start to think this error message means that we're trying to access an index that doesn't exist in that a rate. It's out of the range of the rape. Well, why is that? Because my radar count returns theme number of items in their rate right so it returns three. So our loop actually goes from 0 to 3 inclusive, so it's going to start at zero. It's gonna do one, and that's going to do to. And then it's going to do three. And there is no fourth item in our right, right? This is zero. This is one. This is two. And when it tries to access in next three, there's nothing. And that's why it crashes and gives us this error index out of range. So what we actually have to do when we're working with a race like this and we want toe basically used this count in a loop? We have to do this minus one andan that's going to go from zero to essentially now. It's really good that you know about the Count property now of the array, because that's really useful. But there's actually an even easier way to right this four loop. We can do something like this for each item in my array. Do something with it. That's really the easiest that, um, you know, the easiest that you can get, so you can do you know, if you need the index for some reason and you need to do something with it. You need to reassign something. Then you'd have to use this method where you're accessing where you're getting the index. But if you just want to say, output each item or you want to, you know, use each item without reassigning it into the a rate, then this sort of format is great. What is going to do is it's basically going to loop through every single item in my array and put it into this variable for you to use. So let me comment this part out. Actually, let me let me just comment this whole thing out and just a quick tip. If you want to comment out a whole block of code, you can press a command backslash and that just takes care of that. So we run our code here so you can see this loop very simply, is just printing out the items of the rape. So this is a quick and easy way to loop through items in the rate. All right, Some other cool things. I want to show you how to declare an empty or a I think this is really important to know because right here we are. Initializing this variable to this right? But what really is the data type for this? A rate If you were to explicitly write it Well, I'll tell you it is and the rate So they're square brackets and inside you put the data type of the rate so strength this array can only contain string objects. I forgot to mention that part that your items in the ray will be the same data type. If you wanted to declare an array that is empty to start, you could do something like this. Let's say, Mt. Array so you could just have an empty array like that. But you have to declare the data type because there is no data type inside this anti rate for ex code to determine what data type that rates should be. That's why we have to explicitly specify that right here. Or if you don't do this, you can do something like this. Let's do and t Array two is equal to you could do that as well, So this is basically creating a new or a object, right? This is a type. It's a string rape, and you're basically creating a new object of that string, a rape type, and it's not gonna contain anything by default. All right, now, let me show you some waste to work with the race in terms of adding items and removing items so you can add items first so we can to my array. There's methods like upend, so you can append a new element, or you can even insert so you can insert a new element at a particular index, and it's not gonna override it. It's just gonna push everything back. So let's say I wanted to insert uh, frog at Index zero. Then if I say a copy this down here and I print out the items again, you're going to see that it starts with frog this time. And then it goes. Dog cat bird. So it inserted Froggatt zero and pushed everything else back another way. You can add things you can go plus equals just like that. And then you can add a number of items to the back of the array so I could do frog there. And why don't we move this print statement down here and let's see what is in our array at this point. So we have frog, dog, cat, bird, frog and bear. Oh, and that was That's because I inserted frog at the beginning, and then I appended frog and bare at the back. So that's our resulting A rate. All right, so let me just write it here in case you download the playground. That's another animal that I can use their so many animals out there. Raccoon. It's not like I saw a record out there, but it just popped into my mind, all right, remove items. So my array, it can remove a particular item at a specific index like that. It's going to remove that item, and everything is going to shift to fill its, uh, its place. We can remove all great we can roof first remove last. You can move the first number of items, so there are a lot of options here. Like I said, these collection types are meant to make your life easier to manage collections of data. That's why there are so many handy methods for you to use. Another thing that you might find yourself wanting to do is searching for a specific item in your right, or maybe finding out if an item exists in your array or not. Search your rate, and the method to use for that is there are a couple of options. There used to be one called index of, so you can return to index of the item that you search for. If it doesn't exist in your rate, it would return negative one. Otherwise it will return to actual index. But now there are methods like first index of which returns the first index where the specified value appears because, theoretically, like we saw before frog existed at in egg zero and exist the debt index, maybe six or something like that in our rate. And then, alternatively, there is also last in next of So you're searching from the back towards the front, and it's going to return the last index off that item what you're looking for. So those are a couple of handy ways for you to do some searching within your race. What I have covered in this lesson is enough for you to get the main benefits out of using race. As we continue to build APS together, we're going to learn new ways of using a race, but for now, this is more than enough. Now click on over there for the next lesson, and I'll see you there. 18. 17 - Dictionaries: hi and welcome to my swift tutorial for beginners. In this video, we're going to go through another collection type called the Dictionary. Now these air really common, especially when you're working with data from a remote database or from 1/3 party AP. I All right, stay tuned. I'm looking at the swift documentation here, and they give a really good example about the dictionary collection type. Before we go into the actual example, let's take a look at the differences between dictionaries and race, which we went over in the previous lesson and talked a little bit about what makes them different and when you would use one over the other. So in the previous lesson, when we talked about a raise, I said that it's kind of essentially a list of your data with order zero all the way down sequentially. Now, order matters right. The data at index zero is different from the data at next 12 or three. The dictionary, on the other hand, is unsorted. There is no order. How do you put data into a dictionary while data is put in as key value pairs? So each piece of data that you put into the dictionary, you have to give it an associate ID key to retrieve that piece of data later on. I think of it as kind of like, well, a dictionary where you have maybe the word being the key, right? When you're flipping through a dictionary, you're you're looking for the word. The value that you get from finding that word is the definition. So you can kind of think of it like that or in this case, example that they give is that the value is the airport name, whereas the key is the airport code. Now, one very important thing that I need to stress is that the keys have to be unique, right? Or else it's not gonna work. If you have two different pieces of data with the same key, how are you going to distinguish between the two when you look them up? Now, why don't we jump into the playground and let me show you an example of how to declare a dictionary and some of the ways that we can use it. All right. First, let's declare a dictionary, so I'm gonna say far my dictionary equals and just like an array. You start with to square brackets like that, and then inside you specify the data type of the key, followed by a colon and then the data type of the actual value that you're trying to store . So in this case, I'm gonna put string colon string, which means that my keys are going to be strings and my values are also going to be strength. And just like you saw in the previous lesson about how to declare an empty A rate, you can do the same thing. I mean, a declared an empty dictionary just like this. So essentially, this is the type of the dictionary. All right, so let's go ahead and put some data into our dictionary. So we're gonna type my dictionary, and then we're gonna have to square rockets in an index. You would put the index in here, right? Well, for the dictionary. Instead, you put the key in here now our keys, our strings. Right. So I'm gonna go ahead and put a new string key in here, and then a sign it the value that is going to be associate ID with that. Keep now the example that I want to use is cars and license plates because license plates are unique as well. So why don't we just make one up? So let's say something like that and let's say that this is a red Ferrari. And just like that, I've put in some data into my dictionary with this Associated key. How do we go ahead and retrieve that value? Well, let's try and print that out. First you go in my dictionary, and then you put in the square brackets and you passing your key. So are it Will be S J D. To 93 So let's go ahead and print that. She can see that it is a red Ferrari, but notice that it's wrapped in here in an optional type. The reason for that is because if you try and access, let's say a key that doesn't exist. Let me just make something up. Let's just say one, and there is no key in our dictionary with one you know as the key. When you run it, you actually get nil. So that's why uh, what you get from this is an optional type. It could be a string or could be nil. All right. So I'm going to write down some comments here, assigning data into a dictionary this is declaring and t ST ST Dictionary. This would be retrieving a value as straight so typically, when you try to retrieve the value for this key, you would assign it to something like that. Let's say my car is equal to this, and then you would have to check using one of those methods. We talked in the optionals less than like checking it against nil, using equal equals or using optional binding or anything like that. Okay, so how about placing value for a key? So let's say we changed cars, but we kept the same license plate well, in order to change the data for that key, you would just the sign it something different. So let's call it black Lambeau. All right, so just like that, we've replaced the value for that specific key. Now let's say that you've sold the car and you've kept a license plate. So here's how you remove a value for a key Khost, Neil, simply by assigning it Neil like that, you're essentially removing the data for that key. And the last thing I want to show you is how to iterated or go through the items of the dictionary. Remember, there is no order, but we can still group through the items of of a dictionary by using the four loop. So it would be for something right for something. I don't want to write it right now. I just want fill in the other part for something in my dictionary and then in here do stuff for each item of the dictionary. Now, what is this, Something in here? Well, since dictionaries work in key value pairs, right, so we basically use something called a triple and A to pull. You can think of it as like a collection of variables. And what we're gonna put in here is, let's say key and value. So it's going to take each item out of the dictionary. It's gonna put the key into this variable and is gonna put the value into this variable s so we can do something like this print key. Let's say see what that does Well should put another car in here just to make things a little more interesting. Let's just use Okay, let's try to print this now, So we get our two keys, but we only have one. Ah, that's because we're we removed this car for this key. Why don't we go ahead and comment that out? So we still have two cars in our dictionary and while we run it now, so now you can see the two keys. We can also print out the value. Instead, you'll see are two cars here. Now we can use them separately. We can insert the key, uh, say is a value could do that. So that's how you iterated through a dictionary. So that pretty much wraps up using a dictionary and you will find that it will come in handy alongside using a raise when it comes to organizing your data. Now click on over to the next lesson, and we'll talk over there. 19. Conclusion TUS: Congratulations. You've made it. Thank you so much for learning with B. I really, really appreciate it. For more great tutorials and courses, visit my website at code with chris dot com or visit my YouTube channel at youtube dot com slash code with Chris again. I really appreciate you learning with me. And I hope that we can continue our journey together. All right, bye for now.