0
0
Swiftprogramming~5 mins

Nested functions in Swift

Choose your learning style9 modes available
Introduction

Nested functions help organize code by putting one function inside another. This keeps related tasks together and makes code easier to read.

When you want to break a big task into smaller steps inside a function.
When a helper function is only useful inside one main function.
When you want to hide a function so it can't be used outside.
When you want to keep your code clean and avoid repeating code.
Syntax
Swift
func outerFunction() {
    func innerFunction() {
        // code here
    }
    innerFunction()
}
The inner function is defined inside the outer function's curly braces.
You call the inner function only inside the outer function.
Examples
This example shows a simple nested function that prints a greeting.
Swift
func greet() {
    func sayHello() {
        print("Hello!")
    }
    sayHello()
}
Here, the inner function adds two numbers and the outer function prints the result.
Swift
func calculate() {
    func add(a: Int, b: Int) -> Int {
        return a + b
    }
    let result = add(a: 3, b: 4)
    print("Sum is \(result)")
}
Sample Program

This program defines an outer function with a nested inner function. It calls the inner function inside the outer one and prints messages before and after.

Swift
func outer() {
    func inner() {
        print("This is the inner function.")
    }
    print("Starting outer function.")
    inner()
    print("Ending outer function.")
}

outer()
OutputSuccess
Important Notes

Nested functions can access variables from the outer function.

Inner functions cannot be called from outside the outer function.

Use nested functions to keep helper code private and organized.

Summary

Nested functions are functions inside other functions.

They help organize code and keep helper functions private.

You call inner functions only inside their outer function.