Function in Swift

Create a Function in Swift

Tested on: Xcode 12.3, Swift 5.3

A function is a block of code that runs when you called it. You can pass data or parameters into a function and the function will return data. Then, when your app needs the block of code again, you can simply run the function instead of copying and pasting it over again.


Why do you want to write a function?

A function prevents us from writing the same code over and over again. In this way, there is no duplicated code and reduces the probability of getting an error due to copy and paste.

Look at the code below. You want to buy an ice cream and you write a code to ask your robot to buy it for you. However, after you ate the ice cream, you want to buy another one and you copy and paste the previous code to ask your robot to buy. But there is a problem now, this code looks long and confusing. What you can do is to write a function to reduce make this code reusable and so, when you want to buy an ice cream again. You can just call the functions.

Swift Code :

// Buy one ice cream
print("Walk to the shop")
print("Enter the shop")
print("Buy a ice cream")
print("Pay Money")
print("Come Home")

// Feel like eating an ice cream. Buy one ice cream
print("Walk to the shop")
print("Enter the shop")
print("Buy a ice cream")
print("Pay Money")
print("Come Home")

Once you wrote the buyIceCream function, you can call the function and your robot will but it for you. In this way, your code is short and clean. Therefore, make it easy to understand.

Swift Code :

// Buy one ice cream
buyIceCream()

// Feel like eating an ice cream. Buy one ice cream
buyIceCream()

You will learn the following concepts and this will help you to create a function in Swift.

  1. Basic of Function
  2. Function with Parameters
  3. Return values
  4. Advanced Function





1. Basic of Function

Creating a Function

You can create a function with the func keyword followed by the name of the function and a parenthese. For example, you have an app and you need to print your name frequently. You can write a function as shown below (The name of the function is printMyName).

Swift Code :

func printMyName() {
    print("My name is Wes")
}

However, but creating a function only, does not do anything. Nothing is printed. Therefore, you have to use it by calling this function, printMyName.


Calling a Function

To call a function, you write down the name of the function followed by a parenthese. The example, below will print out my name.

Swift Code :

printMyName()

Output :

My name is Wes




2. Function with Parameters

The example shown in 1, simply print out a message and is not dynamic enough because you want to print your friend name too. In this way, you can perform the function a bit different by passing parameters.

You can define a parameter inside the parentheses after the function name followed by a colon and the data type which is String in this example.

Swift Code :

func printName(name: String) {
    print("Name is \(name)")
}

Now, you can call the function giving the name.

Swift Code :

printMyName(name: "Wes")
printMyName(name: "Swee Kwang")

Output :

Name is Wes

Name is Swee Kwang

2.1 Multiple Parameters

You can also pass in multiple parameters. For example, you want to sum two numbers and you need to function to takes in two values (parameters) as shown below.

Swift Code :

func sumTwoNums(num1: Int, num2: Int) {
    print(num1 + num2)
}

sumTwoNums(num1: 2, num1: 5)

Output :

7


2.2 Default Parameters

You can define a default value for any parameter in function. In this way, when you call the function, you can omit the parameter as it has a value. For example, the default value of num1 is 0 andnum2 is also 0. When you call sumTwoNums function, you are allowed to omit the parameter value as shown below. num1is given a value of 2 while num2 value is not stated and therefore, remain 0.

Swift Code :

func sumTwoNums(num1: Int = 0, num2: Int = 0) {
    print(num1 + num2)
}

sumTwoNums(num1: 2)

Output :

2




3. Return Values

All the functions above only print out stuff and does not return any values. Let's try printing out sumTwoNums function. You can see that two values are printed out. The first output 2 is from the block of code inside the function while the other one ( ) is just an empty value because no value is returned.

Swift Code :

print(sumTwoNums(num1: 2))

Output :

2

()


However, function can also return a value which allow you to assign the return's value to a variable or constant.

To declare a function that return a value, you need to add-> arrows followed by the data type of the return value. Inside the function, you use returnkeyword to return the value.

Swift Code :

func sumTwoNums(num1: Int, num2: Int ) -> Int{
    return(num1 + num2)
}

let newValue = sumTwoNums(num1: 2, num2: 2)
print(newValue)

Output :

4


3.1 Implicit Return

Some functions are not complex like the one above sumTwoNums. Since the function straight away returns a value, you can remove the return keyword.

Swift Code :

func sumTwoNums(num1: Int, num2: Int ) -> Int{
    num1 + num2
}

let newValue = sumTwoNums(num1: 2, num2: 2)
print(newValue)

Output :

4


3.2 Multiple Return Values

Sometimes you have a complex code and you want to return mutiple value. In order to do that, you can state with values with their data type and name before the -> arrows as shown below and return two value seperated by a comma.

Swift Code :

func sumAndSubtractTwoNums(num1: Int, num2: Int ) -> (sumValue: Int, subtractValues: Int ){
    return (num1 + num2, num1 - num2)
}

let newValues = sumAndSubtractTwoNums(num1: 2, num2: 2)
print("newValues: \( newValues) ")
print("sumValue: \( newValues.sumValue) ")
print("subtractValues: \( newValues.subtractValues) ")

Output :

newValues: (sumValue: 4, subtractValues: 0)

sumValue: 4

subtractValues: 0




4. Advanced Function

4.1 Argument Labels (External Name)

Swift Array indexing

In the previous example, the function we created only contains one type of parameter which is called Internal name or parameter name. This parameter name is used for us to access the value enter inside the block of code in the functions and also used it as a name calling the function. However, we can change the name of the parameter when calling by including an External Name or Argument label. This allows us to use a different name when calling the function and using it.

For example, the code below value and valueTwo is the external name which is used to display the name of the parameter when calling it.num1 and num2 is the internal name when is used inside the block of code.

Swift Code :

func sumTwoNums(value num1: Int, valuTwo num2: Int ) -> Int{
    return num1 + num2
}

let newValue = sumTwoNums(value: 2, valuTwo: 2)
print(newValue)

Output :

4


Omitting Argument (External Name)

Some time the external name is not needed and it provide more confusion or making the line of code longer. Therefore, it might be good to remove it.

Swift Code :

func sumTwoNums(_ num1: Int, _ num2: Int ) -> Int{
    return num1 + num2
}

let newValue = sumTwoNums(2, 2)
print(newValue)

Output :

4

4.2 Inout

Sometimes, you want to use the parameter as a variable and change the value you enter. For example the code below, num is multiply by two and assigned back to num. However, you will get an error called "cannot assign to value: 'num' is a 'let' constant".

Swift Code :

func mutiplyByTwo(_ num: Int) -> Int{
    num = num * 2
    return num
}

Output :

error: cannot assign to value: 'num' is a 'let' constant


You can place an inout keyword before the parameter that you will be using it as a variable. Then when calling the function, you need to create a variable and ass an ampersand & before the argument.

Swift Code :

func mutiplyByTwo(_ num: inout Int) -> Int{
    num = num * 2
    return num
}

var number = 2
let newValue = mutiplyByTwo(&number)
print(newValue)

Output :

4