// Define a closure that captures external variables
func makeIncrementer(incrementAmount: Int) -> () -> Int {
var total = 0
// This closure captures 'total' and 'incrementAmount'
let incrementer: () -> Int = {
total += incrementAmount
return total
}
// Return the closure
return incrementer
}
// Create two incrementers with different increment amounts
let incrementerByTwo = makeIncrementer(incrementAmount: 2)
let incrementerByFive = makeIncrementer(incrementAmount: 5)
// Call the closures to see how they capture and maintain state
let result1 = incrementerByTwo() // total = 2
let result2 = incrementerByTwo() // total = 4
let result3 = incrementerByFive() // total = 5
let result4 = incrementerByTwo() // total = 6
// Print the results
print("Result 1: \(result1)")
print("Result 2: \(result2)")
print("Result 3: \(result3)")
print("Result 4: \(result4)")
// The makeIncrementer function returns a closure that increments a variable total by the specified incrementAmount. The closure captures both total and incrementAmount from the surrounding context.
// We create two instances of the closure, incrementerByTwo and incrementerByFive, with different increment amounts.
// Calling the closures multiple times shows how they maintain their captured state. Each closure has its own copy of the captured variables.
// The results demonstrate how the closures remember the values of the captured variables across multiple calls.
// Capturing values in closures can be a powerful tool, allowing you to create functions with persistent state. Keep in mind that closures capture and store references to variables and constants, so changes to the captured variables within the closure affect the original variables in the surrounding context.