Previous episode: 34. Introduction
Next episode: 36. Functions & Return
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
Functions are a core part of a lot of programming languages. Now, basically a function lets you to find a reusable block of code that performs a certain task. So then, whenever your app needs to execute a task, you can just run the function instead of having to copy and paste the same code everywhere. Okay. Let's jump right in and we'll start writing some functions. Let's create a simple function that just prints out a string. I'll choose "Hello". So to write that, I'll start with keyword "func". (keyboard clicks) Then at the name of the function printHello (keyboard clicks) with a pair of parentheses right after it. And finally I'll add a pair of curly braces to create the body of the function. (keyboard clicks) So when you type the first curly brace, the second one should auto complete for you when you press return. Now this part here is called a function declaration. The part inside the curly braces is the body of the function. Just like with loops and if statements, that's where you put the code you want to execute. So I said I just want this function to print out "Hello" and you know how to do that already. (keyboard clicking) And then to use the function, I need to call it from somewhere. Now to call a function, you just type the name of the function followed by parentheses. (keyboard clicking) And once you've called the function, the code inside the body will execute and you can check your results in the sidebar. And in this case, because you're using print, you also get a result in the console. So this process might seem familiar. If you built the bulls-eye app, then you probably remember writing methods like "start new game". So what's the difference between the methods you wrote in bulls-eye and this printHello function? Why is one called the function and the others methods? Now this function isn't part of a struct or a class. The methods in bulls-eye all belonged to the struct they were defined in. Okay now this is an important point to remember about terminology. So you might hear people use the terms "function" and "method" interchangeably. Because methods are essentially functions that belong to another type. So even though they're similar, I really recommend that you be specific when you talk about methods and functions in your code. Now you might also hear the term "free function" used to specify the kind of function I'm talking about. It's free because it isn't owned by a named type like a structure or a class. Okay. Enough about terms, let's get back to some coding. So this printHello function simply print out a message. You probably noticed it's the same message every time you call the function. (keyboard clicks) Print is actually a function too. But when you use print, you can add whatever string you want to be printed to the console inside the parentheses. You'll often want to parameterize your function just like print is. And that means you want the function to do something differently, depending on the data passed into it via its parameters. So for example, take a look at this code from way back in part one of this course. To find out if both students passed, I had to write two nearly identical expressions. (keyboard clicks) Right here. Now I can avoid that code duplication by wrapping the expression in a function that takes the grade as a parameter. So I'll start with the func keyword again, and I'll call this function, printPassStatus. (keyboard clicks) And I'll finish up the declaration with a pair of parentheses and then some curly braces. Nice. So the parameters go inside the parentheses. This is called the parameter list. So this function has just one parameter called grade. I'll make it an int. (keyboard clicks) The syntax for parameters is very similar to what you use to declare variables and constants. You name the parameter, then add a colon and specify the type. So declaring a constant is actually what you're doing. Every parameter becomes a constant you can use inside the body of the function. Now because they're constants, they can't be modified. So let's say you tried to do something like double the grade. Now don't do this, but I will. (keyboard clicks) If you did that, you get an error just like you would if you declared a new constant in the function body with let. Now I can use this grade parameter in an expression just like the ones above to find out if it's a passing grade. (keyboard clicks) If you want to add a more descriptive print statement, you can use a conditional operator to print "You passed" if the expression is true or "Keep studying" if it's false. (keyboard clicks) Now to find out if my function works, I need to call it. When you call a function that uses parameters, you need to pass in arguments. (keyboard clicks) So I've called the function using the samGrade constant as an argument. You can see that the parameter name shows up here. But at the call site, it's called an argument label. The terms parameter and argument are easily mixed up. But it will help you to clearly think and talk about your code if you remember which is which. A function declares it's parameters and it's parameter list. When you call a function, you provide values as arguments for the functions' parameters. Now functions can have more than one parameter. So if I want the option to change the lowest passing grade, I can do that by adding another parameter to the function. When you add more than one parameter to the parameter list, you just comma separate them like this. (keyboard clicks) So now in the body of the function, you can replace passing grade with the new parameter. (keyboard clicks) So if you're following along, your playground should show you an error at this point. This function call is missing an argument to match the new parameter. You can use the "Fix it" to let the playground add the argument label. Or you can add yourself. So I'm going to make it a little tougher for Sam to pass this time. (keyboard clicks) And there Sam's pass status in a console. If you option click on print and scroll down to the bottom of the documentation, you'll see it actually has three parameters. I've only been using this first one - items. So how am I calling the function without providing three arguments? The answer is default values. Print actually has default values for the second two parameters. You can add default values to parameters with the same syntax you use to set values for variables. You just use the assignment operator. That's a single equal sign and the default value you want. (keyboard clicks) So now I can call the function with just the first argument. So you might've noticed one more difference between calling print and calling my print past status function. There's no argument label when you call print. You just put the argument inside the parentheses. In the parameter list, you can add an argument label that's different from a parameter name. But you can also say you don't want an argument label at all. So for example, if I was to write a function to print the highest grade when given two grades. (keyboard clicking) So neither of those parameter names are really necessary when I call the function. I'll call it here. (keyboard clicking) Now the function name already tells us exactly what's going to do with those two arguments. Argument labels are defined right before the parameter name in the parameter list. So we can use our good old friend the underscore there to say I don't need an argument label for this parameter. (keyboard clicking) Now I can leave off both argument labels at the call site and simply separate the arguments with a comma. (keyboard clicks) So in this particular function, I'm following Apple's naming guidelines. If you have arguments that can't be usefully distinguished, you can leave off all the argument labels. So here all I'm doing is comparing two numbers and printing the highest value. It doesn't matter which number is assigned to which parameter. So technically you could use underscores for all the argument labels in all of your functions no matter what you're doing with them but I really don't recommend that. It can be challenging to remember how to call your functions or figure out what a function is planning to do with the arguments that you do pass in. You can also assign an argument label that differs from the parameter name. With swift, it's common to hear that should try to make your function calls read like sentences. I can try that with the printPassStatus function by giving grade and argument label before. (keyboard clicking) And then I need to adjust my function calls to match. (keyboard clicking) When you have an argument label that's different from the parameter name, you'll sometimes hear it's called an external name or external parameter name and that's because you use it outside of or external to the function. So choosing to use prepositions as argument labels like this is a stylistic decision. Apple has their own recommendations like the one I decided when to leave off argument labels altogether. Now these functions are printing out results. But what if I want to do something else with the results like store them in variables or use them in expressions? For that, I'll need to make the function return something. I'll show you how to return values and talk more about function naming conventions in the next episode. I'll see you there.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.