7️⃣Functions
Fall 2023 | Vin Bui
Last updated
Fall 2023 | Vin Bui
Last updated
Imagine a large scale application with thousands of lines of code. The codebase would be very messy! To solve this, we need to be able to reuse our code. We can do this with functions.
Functions allow us to define reusable blocks of code. We define a function by using the func
keyword followed by the name of the function (myName
) and open/close parentheses:
If we were to just define this function in the playground, nothing will be printed out. This is because we also need to call the function. We can call the function we previously defined with the following code:
Let’s test this in the playground:
The nice thing about functions is that we can pass in arguments to make our functions a lot more useful. Using the example above, let’s customize our function to make it a lot more versatile:
This function has a parameter called name
which is of type String
and uses string interpolation to output the name. We would then need to pass in an argument to the function call:
Parameters and arguments are commonly confused by many. Arguments are passed into the function through the function call. Parameters are variables in the header of the function definition.
In Swift, we can change the way parameters are named in the function call and inside of the function definition.
In this example, the name of the parameter within the function definition is str
but when we call the function, we use name
. str
is known as an internal parameter and name
is called an external parameter. This may not seem useful at first glance, but it is a very powerful feature once we begin writing code.
We can also use an underscore (_
) as the external parameter.
By doing this, we do not need to provide the external parameter name when passing in our argument in the function call.
Common external parameter names include in
, for
, and with
.
The functions that we defined earlier did not have any return value, meaning that when we called the function, nothing gets sent back to the function caller. However, many of the functions we create will have a return value. To do this in Swift, we use the right arrow (→
) followed by the return type.
The function above will return true
if the argument that we pass in is an even number and false
otherwise.
Because this function returns a value, we can do many things with this function call such as assigning the returned value to a variable.
If our function returns a value with only one line of code, we can omit the return
keyword. This is commonly seen in SwiftUI.