← 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.

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
func processOrder(itemCount: Int, pricePerItem: Double) -> Double {
    func applyDiscount(_ total: Double) -> Double {
        return itemCount > 5 ? total * 0.9 : total
    }
    let subtotal = Double(itemCount) * pricePerItem
    return applyDiscount(subtotal)
}
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
func makeCounter() -> () -> Int {
    var count = 0
    func increment() -> Int {
        count += 1
        return count
    }
    return increment
}
let counter = makeCounter()
print(counter())
print(counter())
print(counter())
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.