7 days of WordPress plugins, themes & templates - for free! Unlimited asset downloads! Start 7-Day Free Trial
FREELessons: 30Length: 4.8 hours

Next lesson playing in 5 seconds

Cancel
  • Overview
  • Transcript

5.1 Intro to Functions

By this point, your understanding of the Swift language is coming along nicely. But, to be honest, what we have covered will only get you so far. In order to write clean software, we need a way to logically group some functionality. This will make our code not only more reusable but also easier to read, with less duplication. Enter functions.

5.1 Intro to Functions

The next topic that I would like to spend a few lessons discussing in the world of Swift is that of functions. Now functions are not new to the world of Swift or to many other programming languages for that matter. But there are definitely some differences in Swift functions that you probably won't see or may not see in other languages. Now what exactly is a function? Well, a function is nothing more than really just a self-contained block of code that's gonna perform a task. And we can then reuse that function to be able to redo that same task over and over again. So we don't have to continually copy and paste code from one section of our application to another. We can encapsulate that functionality into this block of code into this function. And then ultimately reuse it for the sake of keeping our code nice and clean. So how do we actually defined functions and use functions in the world of Swift? Well, it's quite simple really. We've started to touch on this topic a little bit in some previous lessons. But it's time to really dig down a little bit deeper now, so we simply create a function by specifying the func keywords. That's going to tell us as well as the Swift language and compiler that we are about to define a function. Now we need to give a function a name, so I can call this myfunction. I can really call this anything that I would like, but the general rule of thumb here is to specify the name of the function to really describe what exactly the function is going to do. So maybe myfunction is not necessarily a good name, so instead of doing that maybe it should be sayHello. So as you can tell, this function called sayHello is probably going to give some sort of greeting. Sort of be very simple. So now the next part of the function is we're going to define the function parameters. That are ultimately going to be passed into the function others, a lot of things that we can discuss about different ways to do that. And we'll touch on it a little bit here and we'll talk about it more in the next lesson, because it's a fairly lengthy concept to really get into. But we're going to define those parameters with an open and close parentheses. And this can be some sort of comma separated list if you will, of different parameters. So you could either define them in there or you can leave it empty. So we're gonna start by leaving it empty which means we're not going to provide any input to this function, it doesn't need it. And then after that, we can then define a return value. And a return value within a Swift function is actually specified at the end of the function definition. Where we are going to specify an arrow hear, the minus greater than sign. And then we're gonna specify a type, so are we going to return an Integer or a String or some other type. And there's a number of different things that you can specify here. You can really return any type, any sort of built in type, any sort of custom type. You can return tuples or topples or you could do all sorts of crazy things like that. And we'll talk about that a little bit more in a few moments. So for now though, we can actually specify the fact that there will not be a return value. And we're just going to have this function take no inputs, have no outputs and it's just going to do something. So now we're gonna specify the body of the function, and the body is contained within two curly brackets. And you can split these up our view like I tend to put the open curly bracket on the same line as the function definition. But you can put it down on the next line as well, however you really like to do it. So leave this up here and now within the body of our function, we can define whatever sort of functionality we would like. And at this point, I think these sayHello function will really just do that, so we'll go ahead and say we're going to print Hello. So it's a very simple function, doesn't really do a whole lot, but it really serves a purpose, so I'm gonna save this. And now I have a function, I have this piece of code, this block of reusable code somewhere in my application. And now I wanna use it, so how do I actually call this function? Well, we call this function simply by typing its name, so in this case sayHello. And you're gonna see here that when we type sayHello, we're going to get a little bit of a hint here as to what we might wanna do. And we're gonna be shown a couple different pieces of information, we're gonna be shown the name of the function. We're gonna be shown the inputs that are are required or the parameters which in this case are empty. As well as the return type of void since we don't really have a return. So we can simply call our function just like this and I'll go ahead and save this and I'll run it. And you'll see that our output is going to wind up being Hello, so that's pretty basic stuff there. We have written a function called sayHello that does nothing more than prints a string, print Hello. So while this will work, you're gonna see that this is actually quite boring and we're not really able to do much with this. So if I wanted to add some additional functionality to this, I might want to extend this a little bit. To maybe take a parameter that's going to ultimately let us say hello to someone. So the way that we're going to do that is we're going to come up to our function definition and we're gonna pass in a parameter. So now the way to pass parameters into functions within Swift. Maybe a little bit different if you've come from a world outside of development on the Apple platform. But if you've done any sort of previous Swift development or even Objective-C development. This is not going to seem too strange to you. So the way that we do this is we specify the parameter name that we're going to refer to that parameter as within our function. So I'm gonna say name and then I'm going to specify the type which is gonna be the colon with a type next to it. So I'm going to specify that my sayHello function is going to take in a single parameter whose name is name and whose type is a String. So now that I have defined that, I'm going to assume that I'm going to pass this in to my function. And then I can do something with it, so instead of just printing out Hello. I can now maybe do a little bit of string concatenation there and I could say Hello, name. Just like this. So now I can save this and as you can see now once I've done that, I get a little red exclamation point down here. It says that we're missing an argument for parameter number 1 in our call. So if I come back again and I get rid of this and I start to type sayHello again. You're gonna see that it takes an input parameter of type string who has a name of name, so I can come in here. And I can pass in a name, I could say John. And I can save this and I can run it. And this time I'm going to get Hello, John. So as you can see now, I can start to pass parameters into my function and do something with it. Now I could pass multiple parameters in here, I don't have to be stuck with just one. I could do something like pass in a second parameter here maybe and we'll call this alreadyGreeted. And then this will be a type of Boolean. So at this point now, I can do something with this particular input as well, so I could put a little logic in here. And I could say if alreadyGreeted, then I could do something like, I will copy this block and I will say Hello again with the name. Else, I can go ahead and simply just print out Hello. So now we'll come down here and will save this. And once again we're gonna get a problem here, because we are missing now parameter number 2 which is of type Boolean. So I can come in here now and will once again start typing this in. And we're gonna see that we have two parameters now, a name which is a String and alreadyGreeted which is a Boolean. And you're gonna see something very interesting happen now. So the first parameter, we're gonna jump into here, we're gonna start to type in a name here, so we'll say Amanda. And then we're going to tab over and we're gonna say true that we have already greeted this person out. What seems a little strange about this call to this function? Well, the call to this function looks strange because we're specifying the name of the parameter for this second value but not for the first one. So what we're missing here actually is name at the first parameter. Now as you see here, if I try to pass this in here to give this a name parameter. I'm gonna get a circle here that's gonna say Extraneous argument label name. Which means we don't need it and actually it's more so, it's more than we don't need it, it's we can't have it there. It's just a convention that is included within the Swift programming language. And the way that it's going to work is that if we have multiple parameters here. Then we're only gonna specify the parameters after the first by name. The first one is not needed, so we'll go ahead and save that and we'll run it. So now it will say Hello again, Amanda. And if we were to change this back to false, we'll save this and run this. It will just say, Hello, Amanda. So as you can see now, we can pass multiple values into our function and do some sort of logic around it. Now granted this is a fairly simplistic example, but I think you're starting to get the point. So now we're able to pass data into it, what if we wanted to get data out of it? So once again to specify an output parameter, we come to the end of the first line of our function definition here. And we're gonna specify our arrow and then we need to specify the return type. So in this case, we'll go ahead and specify that we're going to return a String in this case. And now just by the fact that we've done that, I could save this and I could try to build it but it's gonna fail. Because Swift is going to say that we're missing your return value for a function that is expecting to return a String. So at some point in here, for all code paths we are going to have to specify a return. And what I mean by all code paths, is if I were to come into If here and I would put a return statement in here. I will just return an empty string and I try to save this and build. Then it's still not going to work because we are missing a return function for all paths. So in order for this to work we have to make sure that all paths include a return statement that's going to return the expected value. So to do that we're gonna put it down here at the bottom, so I'll go ahead and do a return. And we'll restructure this just a little bit, so instead of printing things out with in our Hello here, we'll simply just return a String. So we'll say, var greeting and we'll initially set this to an empty string and then we'll just put these things together here. We'll say greeting is going to be equal to Hello and then we'll do the same thing down here. Depending on the code path, greeting is gonna be equal to Hello, like that. And then down at the very bottom, we are going to return greeting, so we'll go ahead and save that. Now we'll try and build, and the build is going to succeed. So now at this point, we are doing the same basic type of functionality here. But instead of printing within here, we're simply passing data back. And then we need to do something with it, so how do we get that data back? Well now, this particular function, if we were to look at the definition. And once again you can hold down the Option key and we'll get this little question mark and we can hit the click on it. And we'll see that we've created a function called sayHello with two parameters and an output of String. So what we're gonna need to do is we're going to need to say let greeting. Or whatever variable you want or constant you want to call it be equal to sayHello. And then down here at the bottom, we can simply say print greeting. So we'll save that and we'll build it. Everything build successfully and we'll go ahead and run. And now we're going to get Hello, Amanda because we've passed an alreadyGreeted as false but we could pass it in as true. And go ahead and run again. And we're gonna get Hello again, Amanda. So this is pretty nice, but let's just say for argument's sake that we wanted to return multiple pieces of information. Now on other languages, you may be familiar with out parameters or things of that nature where I can pass in parameters in my inputs. And then we could also specify outputs which basically just marks a parameter saying this parameter can change. So you can check on it later and other languages like C Sharp will do something very similar to that. Where it will pass something in as an output parameter and then we can use that later on. Well, while you can do that, it's somewhat difficult to read that. It's one of the things I like about Swift, is that it gives you the opportunity to return a tuple. So you don't have to worry about doing that. Now you can do something similar to that in Swift by specifying a parameter as being an in out parameter. Which is ultimately going to do the same thing as say passing something in as an output parameter, so I can check it later on. Which basically just means, the body of my function can change the value of this parameter and then we can check it later on. But for purposes of using multiple output values in Swift, I really think that using a tuple as a return value is a much better option. So in this case, let's say we wanted to return a string. And just for argument's sake we'll return an Integer in our tuple. So we're going to return a tuple here that's going to contain a String and an Integer, it could be anything you want. It could be two values, it could be five values, whatever you really like. So you're gonna see now, we are going to get an error here because it's trying to return just a string. But it can't convert that into a return type of a tuple containing a String in an Integer. So we need to return this as a tuple, so we'll return greeting. And we'll just throw in 1 as some sort of arbitrary number, just so that we can see how this would work. And so that now what we can do is we can refer to these values that we're going to get out as greeting, we could do .0 and .1. Remember when we discussed tuples earlier that that's how you by default can refer to them. But I can also come in here and specify names for my tuple. Or the names for the different values in my tuple, I could specify maybe gretting.a or b. So in this case, I'll simply do a, we'll save it and we'll run it. And there you have it, Hello again, Amanda. So that is the basic process of creating very simple functions, we create a function with a name. We give it some arbitrary list of input parameters either from zero up to some number, whatever it takes. Then we can have the option of specifying an output parameter or return type if we would like. Which could be a basic built-in type or a tuple or a custom type or whatever have you. And then we can create the function body. And then ultimately call it simply by using its name. Now in the next couple lessons, we're gonna dig a little bit deeper into some of the finer points of functions. As in some of the nuances of working with the input parameters, as well as talking about closures.

Back to the top