Nested Functions in Swift

Similar to Nested if-statements, when a function co-exists within the body of another function is called a Nested Function. There are 2 main parts to a Nested Function, the inner function that is placed inside the body of the outer function, more commonly known as the enclosing function. An enclosing function can contain more than 1 inner function.

These types of functions are useful because the inner functions in a nested function can only be accessed by the enclosing function, and will not work if called outside that scope. Another big advantage is Encapsulation, you can access these methods without the need to create objects for setting up a connection, making them more practical and readable in advanced projects consisting of thousands of files and objects.

Basic Syntax of a Nested Function

To create a simple Nested Function in Swift, we can use the following structure:

// Outer or Enclosing function
func enclosingFunc() {

  //inner function 1 
  func innerFunc1() {
    
  }
  //inner function 2 (there can be more than 1 if needed)
  func innerFunc2() {

    //You can have multiple layers of function within the inner functions as well
    func innerFunc3() { 
    
    }
  }
}

As shown there are 2 inner functions (innerFunc1 and innerFunc1) inscribed within the outer function (enclosing function). However, you can also inscribe other sub-functions (innerFunc3)within another inner function (innerFunc2).

Practical Examples of Nested Functions

To understand the benefit and control flow of Nested Functions, let us consider the following analogical example: A bank. Suppose that the following code is the backend of a bank application, and the bank users are defined by attributes such as “Name”, “Account Balance” and “Loans”.

func showName(){ 
   print("Vivek") 
}

func showAccountBalance() {
   print("50000.00")
}

func showLoans() {
   print("None"))
} 


showName()
showAccountBalance()
showLoans()

As shown, to display the basic information about a user “Vivek”, we needed to create 3 different methods and call them 3 different times. In reality, thousands of people are associated with a bank, so to make the code efficient we can get the same results using a Nested Function:

//enclosing function
func getBankDetails() {

  // inner functions:
  func showName() {
    print("Vivek")
  }

  func showAccountBalance() {
    print("50000.00")
}

 func showLoans() {
  print("None"))
 } 
}

getBankDetails()
//Output in both cases
Vivek
50000.00
None

Clearly, both programs result in the same output, but example 1 is far more redundant than example 2, which makes it much more concise and preferred.

 

You are not limited to void functions, it is common to nest return functions for certain applications. Let us explore a simple calculator app using net functions:

func findAccelaration(initVelocity: Int, finalVelocity: Int, time: Int, distance: Int) -> Float {
      
      func equation1() -> Float{
          return (finalVelocity - initVelocity)/time
      }
           
      func equation2() -> Float{
          return (2 * (distance - initVelocity * time))/(time*time)
      }

      func equation3() -> Float{
          return (finalVelocity*finalVelocity - initVelocity*initVelocity)/(2 * distance)
      }
}
  
var accelaration = findAccelaration(initVelocity: 0, finalVelocity: 4, time: 5, distance: 10)
print("Result:", result)

Using this, we can return the acceleration using Nested Functions in each case. This is practical because any of the 3 functions can be used depending on what attributes are assigned. For example, if only time, distance and initVelocity are given, the enclosing function can use equation2.

 

Also read: If NOT Conditional case in Swift

Leave a Reply

Your email address will not be published.