← Back to Swift Course | Chapter 7: Closures | Lesson 1 of 6

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.
Syntax
swift
let closureName = { (param: Type) -> ReturnType in
    return value
}

functionName(argument, using: { (param: Type) -> ReturnType in
    return value
})

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

markup
// Declare a constant `multiply`, set to `{ (a: Int, b: Int) -> Int in`
let multiply = { (a: Int, b: Int) -> Int in
    // Return `a * b` from this function
    return a * b
}
// Print `multiply(3, 4)` to the console
print(multiply(3, 4))

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

markup
// Define the function `operate` taking `a`, `b`, `operation` and returning an Int
func operate(_ a: Int, _ b: Int, using operation: (Int, Int) -> Int) -> Int {
    // Return `operation(a, b)` from this function
    return operation(a, b)
}
let result = operate(5, 6, using: { (x: Int, y: Int) -> Int in
    // Return `x + y` from this function
    return x + y
})
// Print `result` to the console
print(result)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the in keyword that separates a closure's parameter list and return type from its body.
  2. Writing unnecessary type annotations inside a closure when Swift can already infer them from context.
  3. Confusing closure syntax { (params) -> ReturnType in ... } with a function's func declaration; closures never use the func keyword.
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:

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.