Nested Functions
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
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))
Login to try C/C++/Java/PHP code in the editor
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
func makeCounter() -> () -> Int {
var count = 0
func increment() -> Int {
count += 1
return count
}
return increment
}
let counter = makeCounter()
print(counter())
print(counter())
print(counter())
Login to try C/C++/Java/PHP code in the editor
- Trying to call a nested function from outside its enclosing function; its scope is limited to where it's declared.
- Overusing nested functions for logic that would be clearer and more reusable as a top-level function.
- Forgetting that a nested function can capture and use variables from its enclosing function's scope, just like a closure.
- 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: