Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. Closures (Basics) / { } / in

Closures (Basics) / { } / in

A closure in Swift is an anonymous function that bundles a block of code and can be stored in a variable or passed as an argument. Closures are written in the form { arguments in body }.

Syntax

// Basic closure form
{ (parameterName: Type) -> ReturnType in
    return value
}

// Assign a closure to a variable
let closureName: (ParameterType) -> ReturnType = { parameterName in
    return value
}

// Type alias for a function type
typealias TypeName = (ParameterType) -> ReturnType

Syntax List

SyntaxDescription
{ (param: Type) -> ReturnType in body }The full closure syntax with explicit types.
{ param in body }A shorthand form where types are inferred.
let f: (Int) -> Int = { ... }Assigns a closure to a variable.
func name(completion: (Type) -> Void) { }Defines a function that accepts a closure as an argument.
closure(argument)Calls a closure stored in a variable.

Sample Code

// Assign a closure to a variable
let greet: (String) -> String = { (name: String) -> String in
    return "Hello, \(name)!"
}
print(greet("Taro"))

// Shorthand using type inference
let double: (Int) -> Int = { number in
    return number * 2
}
print(double(5))

// Closure with no return value
let printMessage: (String) -> Void = { message in
    print("Message: \(message)")
}
printMessage("Hello, Swift!")

// Passing a closure as an argument
func applyOperation(_ value: Int, operation: (Int) -> Int) -> Int {
    return operation(value)
}

let tripled = applyOperation(4) { number in
    return number * 3
}
print(tripled)  // 12

// Capturing surrounding variables (a key closure feature)
func makeCounter() -> () -> Int {
    var count = 0
    let counter = { () -> Int in
        count += 1
        return count
    }
    return counter
}

let counter = makeCounter()
print(counter())  // 1
print(counter())  // 2
print(counter())  // 3

Notes

Closures can capture variables and constants from their surrounding scope. In the makeCounter example above, the closure captures the count variable from the function's scope and keeps it alive even after the function returns.

Closures are reference types. Assigning the same closure to multiple variables shares the captured values. When a closure captures self, be careful of retain cycles — use a capture list with [weak self] to avoid them.

For shorthand syntax and trailing closures, see Trailing Closures / Shorthand / $0.

If you find any errors or copyright issues, please .