← Back to Swift Course | Chapter 4: Functions | Lesson 7 of 7

Nested Functions

A nested function is a small helper function defined right inside another function, only usable there.
Syntax
swift
func outerFunction() {
    func innerFunction() {
        // can use outerFunction's variables
    }
    innerFunction()
}

Defining a Nested Function

A function declared inside another function's body is scoped only to that enclosing function and helps organize multi-step logic.

Example: Defining a Nested Function

markup
// Define the function `processOrder` taking `itemCount`, `pricePerItem` and returning a Double
func processOrder(itemCount: Int, pricePerItem: Double) -> Double {
    // Define the function `applyDiscount` taking `total` and returning a Double
    func applyDiscount(_ total: Double) -> Double {
        // Return `itemCount > 5 ? total * 0.9 : total` from this function
        return itemCount > 5 ? total * 0.9 : total
    }
    // Declare a constant `subtotal`, set to `Double(itemCount) * pricePerItem`
    let subtotal = Double(itemCount) * pricePerItem
    // Return `applyDiscount(subtotal)` from this function
    return applyDiscount(subtotal)
}
// Print `processOrder(itemCount: 8, pricePerItem: 10.0)` to the console
print(processOrder(itemCount: 8, pricePerItem: 10.0))

Nested Functions Capturing Outer Variables

A nested function automatically has access to the constants and variables of its enclosing function, without needing them passed in explicitly.

Note: This pattern -- returning a nested function that captures state -- is the foundation of closures, covered in a later chapter.

Example: Nested Functions Capturing Outer Variables

markup
// Define the function `makeCounter` with no parameters and returning a `() -> Int`
func makeCounter() -> () -> Int {
    // Declare a mutable variable `count`, initialized to `0`
    var count = 0
    // Define the function `increment` with no parameters and returning an Int
    func increment() -> Int {
        count += 1
        // Return `count` from this function
        return count
    }
    // Return `increment` from this function
    return increment
}
// Declare a constant `counter`, set to `makeCounter()`
let counter = makeCounter()
// Print `counter()` to the console
print(counter())
// Print `counter()` to the console
print(counter())
// Print `counter()` to the console
print(counter())
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to call a nested function from outside its enclosing function; its scope is limited to where it's declared.
  2. Overusing nested functions for logic that would be clearer and more reusable as a top-level function.
  3. Forgetting that a nested function can capture and use variables from its enclosing function's scope, just like a closure.
Chapter Summary
  • A function defined inside another function is only visible within that enclosing function.
  • Nested functions can capture variables from their enclosing scope.
  • They help break a complex function into smaller, well-named private steps.
  • A nested function can be returned from its enclosing function if the enclosing function's return type is a matching function type.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.