Swift - Functions



A function is a set of statements organized together to perform a specific task. A Swift function can be as simple as a simple C function to as complex as an Objective C language function. It allows us to pass local and global parameter values inside the function calls. Also, we can define a function inside another function to encapsulate its functionality inside another function.

Function plays an important role in structuring code, modularity and increasing code readability. They also provide various features such as parameter labels, default parameter values, variadic parameters, and multiple return types.

Function Definition in Swift

In Swift, a function is defined by the "func" keyword. When a function is newly defined, it may take one or several values as input 'parameters' to the function and it will process the functions in the main body and pass back the values to the functions as output 'return types'.

Every function has a function name, which describes the task that the function performs. To use a function, you "call" that function with its name and pass input values (known as arguments) that match the types of the function's parameters. Function parameters are also called as 'tuples'.

A function's arguments must always be provided in the same order as the function's parameter list and the return values are followed by ->.

Syntax

Following is the syntax for creating a function −

func funcname(Parameters) -> returntype {
   Statement1
   Statement2
   ---
   Statement N
   return parameters
}

Example

Swift program to demonstrate how to create a function.

// Function with return type
func student(name: String) -> String {
   return name
}

print(student(name: "First Program"))
print(student(name:"About Functions"))

Output

It will produce the following output −

First Program
About Functions

Calling a Function in Swift

Calling a function means executing the set of statements present inside the function. We can call a function through its name and at the time of calling it is necessary to provide all the arguments (if available).

Let us suppose we defined a function called 'display' to Consider for example to display the numbers a function with function name 'display' is initialized first with argument 'no1' which holds integer data type.

Then the argument 'no1' is assigned to argument 'a' which hereafter will point to the same data type integer. Now the argument 'a' is returned to the function. Here display() function will hold the integer value and return the integer values every time the function is invoked.

Syntax

Following is the syntax for calling a function −

funcName(parameters)

Example

Swift program to demonstrate how to call a function.

// Creating function
func display(no1: Int) -> Int {
   let a = no1
   return a
}

// Calling function
print(display(no1: 100))
print(display(no1: 200))

Output

It will produce the following output −

100
200

Type of Function Parameters in Swift

Parameters are the variables that are specified in the function declaration to get input when the function is called. Or they allow us to pass values to the function at the time of calling and can perform operations on those values. They are always specified inside the function along with the label, type and value(if available). Swift function supports the following types of parameters −

  • Regular Parameters
  • Varadic Parameters
  • In-Out parameters

Let us discuss all types of parameters in detail.

Regular Parameters

Regular parameters are the most commonly used parameters in the function. They allow us to perform basic operations according to the specified value. A function can have a single or multiple regular parameters. Each regular parameter has its argument label, and explicit type and they are separated by comma.

We can also specify the default value in the regular parameter, which means if we omit that parameter while calling that function, then the default value present in that parameter will used.

Syntax

Following is the syntax for regular parameters −

func funcname(name1: Type, name2:Type = defualtValue) -> returntype {
   Statement
   return value
}

Example

Swift program to demonstrate how to create a function with regular parameters.

// Creating function with regular parameters and default value
func Sum(num1: Int, num2: Int = 2) -> Int {
   var result = 0
   result = num1 + num2
   return result
}

// Calling function 
print("Sum 1:", Sum(num1: 10))
print("Sum 2:", Sum(num1: 20, num2: 12))
Output

It will produce the following output −

Sum 1: 12
Sum 2: 32

Variadic Parameters

Swift provide a special type of parameter named a varadic parameter. The variadic parameter allows us to accept multiple input values of the same type in the function. This parameter is useful when we want to pass an arbitrary number of values of the same type inside the function without specifying the exact count of the values.

A single function can contain multiple variadic parameters and after the first variadic parameter, the next variadic parameters must contain argument labels to distinguish them. The values passed inside the variadic parameters are available as an array in the function. A variadic parameter is not marked as inout.

Syntax

Following is the syntax for variadic parameters −

func funcname(_name1: Type…, name2:Type…, name3: Type…) -> returntype
{
   Statement
   return value
}

Example

Swift program to demonstrate how to create a function with varadic parameters.

// Creating function with variadic parameter 
func Product(_ num: Int...) -> Int {

   var result = 1
   for x in num{
      result *= x
   }
   return result
}

// Calling function and passing multiple values of the same type
print("Product:", Product(10, 20, 30))
Output

It will produce the following output −

Product: 6000

In-Out Parameter

In-Out parameters in Swift provide the functionality to retain the parameter values even though their values are modified after the function call. At the beginning of the function parameter definition, 'inout' keyword is declared to retain the member values.

It derives the keyword 'inout' since its values are passed 'in' to the function and its values are accessed and modified by its function body and it is returned back 'out' of the function to modify the original argument. The in-out parameter does not contain a default value.

Variables are only passed as an argument for in-out parameters since their values alone are modified inside and outside the function. Hence no need to declare strings and literals as in-out parameters. '&' before a variable name refers to that we are passing the argument to the in-out parameter.

Syntax

Following is the syntax for In-Out parameters −

func funcname(_name1: inout Type, _name2: inout Type) -> returntype
{
   Statement
   return value
}

Example

Swift program to demonstrate how to create a function with in-out parameters.

// Function to swap two values
func swap(_ x: inout Int, _ y: inout Int) {
   let temp = x
   x = y
   y = temp
}

var p = 15
var q = 10

print("Before swapping: p = \(p), q = \(q)")

swap(&p, &q)

print("After swapping: p = \(p), q = \(q)")
Output

It will produce the following output −

Before swapping: p = 15, q = 10
After swapping: p = 10, q = 15

Function Argument label and Parameter name in Swift

A function can have labels and names for its arguments and parameters. These labels and names provide a clear and descriptive context for the argument and parameter. The parameter name is used in the declaration of function whereas argument label is used when the function is called.

By default, the argument label and parameter name are the same, but multiple parameters can have the same or unique argument label. The names of the parameters should be unique so that the function can easily distinguish them. We can also omit the argument label by placing the underscore(_) before the name of the parameter.

Syntax

Following is the syntax for the argument label and parameter name −

// Parameter name With argument label
func funcname(argumentLabel parameterName: Type, parameterName: Type) -> returntype {
   Statement
   return value
}
funcname(name1:value, name2: value)

// Parameter name without argument label
func funcname(_name1: Type, _name2: Type) -> returntype {
   Statement
   return value
}
funcname(value1, value2)

Example

Swift program to demonstrate how to specify parameter name and argument label in the function.

// Function 1 with parameter names and argument label
func pow(firstArg a: Int, secondArg b: Int) -> Int {
   var res = a
   for _ in 1..<b {
      res = res * a
   }
   return res
}
print("Power:", pow(firstArg:5, secondArg:3))

// Function 2 with parameter names and without argument label
func product(_ a: Int,  b: Int) -> Int {
   let res = a * b
   return res
}
print("Product:", product(5, b:3))

Output

It will produce the following output −

Power: 125
Product: 15

Parameters and Return Values in Swift

Swift provides flexible function parameters and its return values from simple to complex values. We can create functions in various forms such as −

  • Function with parameters

  • Function without parameters

  • Function with return type

  • Function without return type

  • Function with optional return type

Let's discuss all the forms of function in detail.

Functions with Parameters

A function is accessed by passing its parameter values to the body of the function. We can pass single or multiple parameter values inside the function and each parameter has its own label so that the compiler can identify which corresponds to which parameter.

Syntax

Following is the syntax for a function with parameters −

func funcname(para1: Type, para2: Type) -> datatype {
   return datatype
}

Example

Swift program to create a function with parameters.

// Function with two parameters
func mult(no1: Int, no2: Int) -> Int {
   return no1 * no2
}

// Calling function
print(mult(no1: 2, no2: 20))
print(mult(no1: 3, no2: 15))
print(mult(no1: 4, no2: 30))
Output

It will produce the following output −

40
45
120

Functions without Parameters

We can also define a function without any parameters. Such types of functions are useful when we want to encapsulate a block of code that does not depend upon any external inputs.

Syntax

Following is the syntax for a function without parameters −

func funcname() -> datatype {
   return datatype
}

Example

Swift program to create a function without parameters.

// Function without parameters
func votersname() -> String {
   return "Alice"
}

// Calling function
print(votersname()) 
Output

It will produce the following output −

Alice

Functions with Return Values

Functions are also used to return string, integer, and float data type values as return types. It can return single or multiple values. If the function returns multiple values then it will use tuple to return multiple values.

Syntax

Following is the syntax for a function with return value −

func funcname(para1: Type, para2: Type) -> datatype {
   return datatype
}

Example

Swift program to create a function that returns a value.

// Function to find out the largest and smallest number in a given array 
func ls(array: [Int]) -> (large: Int, small: Int) { 
   var lar = array[0]
   var sma = array[0]
   
   // Comparing value with its previous value
   for i in array[1..<array.count] 
   {
   
      // If the value is lesser than the previous one it is stored in 'sma' argument
      if i < sma {
         sma = i
      }
      // Otherwise it is stored in 'lar' argument
      else if i > lar {
         lar = i
      }
   }
   
   // Returning multiple values using tuple
   return (lar, sma)
}

let num = ls(array: [40, 12, -5, 78, 98])
print("Largest number is: \(num.large) and smallest number is: \(num.small)")
Output

It will produce the following output −

Largest number is: 98 and smallest number is: -5

Functions without Return Values

Some functions may have arguments declared inside the function without any return values

Syntax

Following is the syntax for a function without return type −

func funcname(para1: Type, para2: Type){
   return datatype
}

Example

Swift program to create a function that does not return a value.

// Function with parameters but no return type
func sum(a: Int, b: Int) {
   let a = a + b
   let b = a - b
   print(a, b)
}

sum(a: 20, b: 10)
sum(a: 40, b: 10)
sum(a: 24, b: 6)
Output

It will produce the following output −

30 20
50 40
30 24

Functions with Optional Return Types

Swift introduces an 'optional' feature to get rid of problems by introducing a safety measure. 'Optional' is used to check 'nil' or garbage values thereby consuming a lot of time in debugging and making the code efficient and readable for the user.

Consider for example we are declaring function values return type as integer but what will happen when the function returns a string value or a nil value. In that case, the compiler will return an error value. 'optional' is introduced to get rid of these problems.

Optional functions will take two forms 'value' and a 'nil'. We will mention 'Optionals' with the key reserved character '?' to check whether the tuple is returning a value or a nil value.

Example

Swift program to create a function that returns an optional type.

// Function with optional return type
func minMax(array: [Int]) -> (min: Int, max: Int)? {

   if array.isEmpty { return nil }
   var currentMin = array[0]
   var currentMax = array[0]
    
   for value in array[1..<array.count] 
   {
      if value < currentMin {
         currentMin = value
      } else if value > currentMax {
         currentMax = value
      }
   }
   return (currentMin, currentMax)
}

if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
   print("min is \(bounds.min) and max is \(bounds.max)")
}
Output

It will produce the following output −

min is -6 and max is 109

Function Types

In Swift, a function type is used to represent the type of function along with its parameter types and return types. The function type allows us to create, pass and use a function as a variable or parameter in a type-safe manner. Parameter type represents what type of parameter are going to be stored in the function whereas return type represents what type of a value the function will return.

Example

Swift program to demonstrate function type.

func inputs(no1: Int, no2: Int) -> Int {
   return no1/no2
}
print(inputs(no1: 20, no2: 10))
print(inputs(no1: 36, no2:6))

Output

It will produce the following output −

2
6

Assign Function to a variable

Swift functions are first-class citizens. So we are allowed to assign a function to a variable just like we assign a value to a variable. After assigning the function to a variable that variable holds the reference of that function.

Syntax

Following is the syntax for assigning function to a variable −

var addition: (Int, Int) -> Int = sum

Here sum is a function name having 'a' and 'b' integer variables which is now declared as a variable to the function name addition. Hereafter both addition and sum functions both have the same number of arguments declared as integer datatype and also return integer values as references.

Example

Swift program to demonstrate how to assign a function to a variable.

// Function
func sum(a: Int, b: Int) -> Int {
   return a + b
}

// Assigning a function to a variable
var addition: (Int, Int) -> Int = sum
print("Result: \(addition(40, 89))")
Output

It will produce the following output −

Result: 129

Function Types as Parameter Types

In Swift, we can use a function type as a parameter type in another function, which means we can pass a function as an argument in another function.

Example

Swift program to demonstrate how to pass a function as a parameter into another function.

// Function type is (Int, Int) -> Int
func add(_ x: Int, _ y: Int) -> Int {
   return x + y
}

// Function type as a parameter
func Display(_ myOperation: (Int, Int) -> Int, _ p: Int, _ q: Int) -> Int {
   return myOperation(p, q)
}

// Passing function as an argument
let sum = Display(add, 5, 7)

print("Sum: \(sum)")       
Output

It will produce the following output −

Sum: 12

Function Types as Return Types

In Swift, we can use a function type as a return type in another function, which means a function can return from another function.

Example

Swift program to demonstrate how a function returns another function.

// Function type is (Int, Int) -> Int
func add(_ x: Int, _ y: Int) -> Int {
   return x + y
}

// Display() function will return add() function
func Display()->(Int, Int) -> Int {
   return add
}

let myFunc = Display()
let result = myFunc(9, 2)

print("Sum: \(result)")
Output

It will produce the following output −

Sum: 11
Advertisements