Swift Nested Functions

In Swift, a function can exist inside the body of another function. This is called a nested function.

Before you learn about nested functions make sure to know about Swift functions.


Syntax of Nested Function

Here's how we create nested functions in swift.

// outer function
func function1() {
  // code

  // inner function
  func function2() {
    // code
  }

}

Here, the function function2() is nested inside the outer function function1()


Example 1: Swift Nested function

Output

Good Morning Abraham!

In the above example, we have created two functions:

  • greetMessage() - a regular function
  • displayName() - an inner function nested inside greetMessage()

Here, we are calling the inner function displayName() from the outer function.

Note: If we try to call the inner function from outside of the outer function, we'll get the error message: use of unresolved identifier.


Example 2: Nested Function with Parameters

Output

Addition
5 + 10 = 15

In the above example, the function display() is nested inside the function addNumbers(). Notice the inner function,

func display(num1: Int, num2: Int) {
  ...
}

Here, it consists of two parameters num1 and num2. Hence, we have passed 5 and 10 while calling it (display(num1: 5, num2: 10))


Example 3: Nested Function with Return Values

Output

Result: 11

In the above example, the functions add() and subtract() are nested inside the operate() function . Notice the declaration of the outer function

func operate(symbol: String) -> (Int, Int) -> Int {
  ...
}

Here, the return type (Int, Int) -> Int specifies that the outer function returns a function with

  • two parameters of Int type and
  • a return value of Int type.

Since this matches the function definition of inner functions, the outer function returns one of the inner functions.

This is why we are able to call the inner function from outside of the outer function as well using

let result = operation(8, 3)

Here, operation(8, 3) is replaced by either add(8, 3) or subtract(8, 3) based on the value of symbol passed to the operate() function.

Table of Contents