Swift: Function vs Closure
Video: Swift: Function vs Closure by Taught by Celeste AI - AI Coding Coach
Watch full page →Swift: Function vs Closure
In Swift, both functions and closures are self-contained blocks of code that can be passed around and used in your programs. While functions have a defined name and structure, closures are anonymous and can capture values from their surrounding context, making them more flexible for inline use.
Code
// A simple named function that adds two numbers
func add(a: Int, b: Int) -> Int {
return a + b
}
// Using the function
let sum = add(a: 3, b: 5)
// A closure that does the same addition, assigned to a variable
let addClosure: (Int, Int) -> Int = { (a, b) in
return a + b
}
// Using the closure
let closureSum = addClosure(3, 5)
// Closures can capture values from their context
func makeIncrementer(amount: Int) -> () -> Int {
var total = 0
// This closure captures 'total' and 'amount'
return {
total += amount
return total
}
}
let incrementByTen = makeIncrementer(amount: 10)
incrementByTen() // returns 10
incrementByTen() // returns 20
Key Points
- Functions are named blocks of code, while closures are anonymous and can be assigned to variables.
- Closures can capture and store references to variables from their surrounding context.
- Closures provide flexibility for inline, concise code, especially for callbacks and functional programming patterns.
- Both functions and closures share the same type syntax and can be used interchangeably in many situations.