©Shutterstock/baranq
In Swift, a function is defined using the func
keyword, like this:
func doSomething() { print("doSomething") }The preceding code snippet defines a function called
doSomething
. It does not take in any inputs (known as parameters) and does not return a value (technically, it does return a Void
value).To call the function, simply call its name followed by a pair of empty parentheses:
doSomething()
Understanding input parameters
A function can also optionally define one or more named typed inputs. The following function takes in one single typed input parameter:func doSomething(num: Int) { print(num) }To call this function, call its name and pass in an integer value (known as an argument) with the parameter name, like this:
doSomething(num: 5)The following function takes in two input parameters, both of type Int:
func doSomething(num1: Int, num2: Int) { print(num1, num2) }To call this function, pass it two integer values as the argument:
doSomething(num1: 5, num2: 6)
Returning a value
Functions are not required to return a value. However, if you want the function to return a value, use the -> operator after the function declaration. The following function returns an integer value:func doSomething(num1: Int, num2: Int, num3: Int) -> Int { return num1 + num2 + num3 }You use the
return
keyword to return a value from a function and then exit it. When the function returns a value, you can assign it to a variable or constant, like this:
var sum = doSomething(num1:5, num2:6, num3: 7)
Functions are not limited to returning a single value. In some cases, it’s important for functions to return multiple values (or even functions). In Swift, you can use a tuple type in a function to return multiple values.
Want to learn more? Check out these SwiftUI tips and tricks.