Closure Syntax
A closure is a chunk of code you can carry around like a value, similar to a function but without needing a name.
In this page:
Full Closure Syntax
The most explicit closure syntax spells out parameter types, return type, and the in keyword before the body.
Example: Full Closure Syntax
let multiply = { (a: Int, b: Int) -> Int in
return a * b
}
print(multiply(3, 4))
Login to try C/C++/Java/PHP code in the editor
Closures as Function Arguments
A closure can be passed directly as an argument to a function expecting a matching function type.
Example: Closures as Function Arguments
func operate(_ a: Int, _ b: Int, using operation: (Int, Int) -> Int) -> Int {
return operation(a, b)
}
let result = operate(5, 6, using: { (x: Int, y: Int) -> Int in
return x + y
})
print(result)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the
inkeyword that separates a closure's parameter list and return type from its body. - Writing unnecessary type annotations inside a closure when Swift can already infer them from context.
- Confusing closure syntax
{ (params) -> ReturnType in ... }with a function'sfuncdeclaration; closures never use thefunckeyword.
Chapter Summary
- A closure is written as
{ (parameters) -> ReturnType in statements }. - Closures can be assigned to variables and called just like functions.
- Type annotations inside a closure are often unnecessary since Swift infers them from context.
- Closures capture and reference variables from their surrounding scope.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: