When you’re first learning to code, you might have all of your code in one big, long file. And that’s perfect for being in the playground and learning how to code.
Once you start building real apps, you’ll have so much code that it won’t be practical to use one big file. Functions let you organize your code into reusable chunks. You’ll create specific files containing functions that you can then call from your code.
When you run an app, one function runs a chunk of code, and then that function calls another function to run a chunk of code, and so on. Your whole app is basically a series of functions calling each other to run chunks of code.
A Very Simple Function
Each function will have its own purpose. You might have one function to handle a button tap, another function to call an API, another to generate a random color, and so on. This helps you keep your code clean and organized.
Each file will have a series of objects and functions, and you’ll write logic inside of those functions.
For example, instead of using this line of code:
print("My function works")
Let’s put this inside of a function.
func exampleFunction() {
print("My function works")
}
- func – this is short for function
- () – parenthesis. This is the initializer for the function. We can pass data into the function using the initializer.
- exampleFunction – this is the name of the function. You’ll name the function whatever makes sense.
- { } – these are curly braces. The code inside will run only when the function is called.
- print(“My function works”) – this is whatever you want the function to do. In this example, it is going to print the string “My function works”. However, it doesn’t have to be a print statement. It can be any logic.
Now, every time we want to run that line of code, we call the function by stating the name of the function with brackets, like this:
exampleFunction()
While this example only saves us a few characters, in practice, the function body will usually be much longer. Calling it with short, clear statements makes your code 1000% more readable.
Multiple Functions
Most apps have many, many functions. Here is an example with just 2 functions:
func firstFunction() {
print("My first function")
}
func secondFunction() {
print("My second function")
}
firstFunction()
secondFunction()
Both of these functions will run, because we have called both of these functions like this:
firstFunction()<br>secondFunction()
The functions will exectute one after another, in order.
Functions Calling Other Functions
You can also embed the functions, so one function can call another. For example, this code will run both functions:
func firstFunction() {
print("My first function")
secondFunction()
}
func secondFunction() {
print("My second function")
}
firstFunction()
Here, the first function is called by stating firstFunction() and then starts to run. In this function, there are 2 steps:
- print(“My first function called”): This will happen first, and it will print “My first function called” in the console
- secondFunction(): Next, the second function is called inside the first function’s closure: secondFunction(). This will execute the code inside of the definition of secondFunction and print “My second function called”.
In this example, since secondFunction() is only called inside of the first function, it will only run if the first function is called.
Defining variables inside a function
When you declare a variable or constant inside of a function, it can only be used inside of that function. You can’t change it outside the context of that function.
In this example, we are defining the variable username inside of the curly braces {}.
func getUserName() {
let username = "Jessica"
print (username)
}
getUserName()
When we are outside of the curly braces we can’t access the constant “username” and reference it elsewhere.
For example, if we were to add the statement let name = username in the below code, it will not run, because it can’t look and see what “username” is, since “username” is private to the function.
This will not work:
func getUserName() {
let username = "Jessica"
print (username)
}
let name = username
getUserName()
You’ll receive the error message: Cannot find ‘username’ in scope if you try to execute this code.
If we were to move let name = username outside of the function, it will be public to everything inside the file. We can still call it from within the function using the statement print (username), and we can access it below in the statement let name = username.
let username = "Jessica"
func getUserName() {
print (username)
}
let name = username
getUserName()
Returning Data from a Function
let username = "Jessica"
func getUserName() -> String {
return username
}
getUserName()
If we want the function to return a value instead of printing, we can do that by:
- declaring the datatype (in this example , we state
-> Stringafter the function name) - using the return keyword inside of the function
Now, when we call getUserName(), it will return us back the string that is coming out of the function.
Setting Variables Equal To The Value Returned By A Function
We’re also able to set variables equal to the value returned by the function, by listing it like this:
let username = "Jessica"
func getUserName() -> String {
return username
}
let name = getUserName()
Remember, Swift is a type-safe language, so the value being returned should be the same data type as the variable.
Control Flow in Functions
Here, we’ll create a Boolean to check user status. We will use a function, and it will return a true or false, based on the data.
var UserDidCompleteOnboarding: Bool = false
var UserProfileIsCreated: Bool = true
func checkUserStatus() -> Bool {
if userDidCompleteOnboarding && userProfileCreated {
return true
} else
return false
}
}
In reality, that process will be a lot more complex. However, you can see the basics of how you can use a function with conditional logic to return data.
In practice, it’s not very common to have variables just floating around the app unless in a playground. You can have variables just in the code, but that’s called a global variable, and it’s generally frowed upon. In a real app, those 2 variables would be inside of some sort of other object or function.
Passing Data Into Functions
You may be wondering why we have the open and close parenthesis after the funciton name. These are called the initializer of the function, and we can pass data into the initializer that we can then use in the function.
Eventually we’ll cover using initializers and creating our own objects a little more, but for now, we’ll look at a simple example of passing data into this function that we can then use.
So if we wanted to pass in values for userDidCompleteOnboarding && userProfileCreated, we would do that like this:
var UserDidCompleteOnboarding: Bool = false
var UserProfileIsCreated: Bool = true
func checkUserStatus(userDidCompleteOnboarding: Bool, userProfileCreated: Bool) -> Bool {
if userDidCompleteOnboarding && userProfileCreated {
return true
} else {
return false
}
}
The funtion understands that we are passing the values inside of the parenthesis, and based on those values, we’ll perform the logic inside of the function.
Returning Void
Sometimes, you will see a function that doesn’t return anything. That is the same thing as returning void, like this:
func doNothing() -> Void {
}
Void is just nothing. Basically it’s having a function that doens’t return anything. There’s no true, there’s no false, there’s no string, there’s no value.
In Swift, the compiler understands that if you don’t put anything after the initializer, it is the same thing as returning a void. You technically don’t need to every use this, however, many people use it in order to
Leave a Reply