What are 'Closures' in Swift and how are they used?
Instruction: Provide an explanation of closures in Swift, including their syntax and typical use cases.
Updated
Official answer
A closure is a function value that can be stored, passed and invoked. A closure expression uses parameters, an optional return type, in, and a body. Closures are useful for collection transformations, callbacks and deferred behavior, and they can capture values from their surrounding scope.
let multiply: (Int, Int) -> Int = { left, right in left * right }
assert(multiply(3, 4) == 12)
let squares = [1, 2, 3].map { $0 * $0 }
assert(squares == [1, 4, 9])
func makeCounter() -> () -> Int {
var count = 0
return {
count += 1
return count
}
}
let counter = makeCounter()
assert(counter() == 1)
assert(counter() == 2)
let independent = makeCounter()
assert(independent() == 1)
These small Int examples use values that do not overflow. The returned closure keeps its captured counter alive after makeCounter returns. Assigning that same closure to another variable shares its capture; another factory call creates different captured state.
A closure parameter is normally nonescaping; mark it @escaping if the callee stores it or calls it after that call returns. Escaping is a lifetime property, not a guarantee that work runs asynchronously or on a background thread. @Sendable expresses restrictions relevant to transferring a closure across concurrency boundaries; it does not create synchronization for arbitrary shared mutable captures.
For a class that stores a closure which captures the class, inspect whether the resulting strong references form a cycle. A weak capture can break the cycle when the operation may outlive the object; handle the nil case. Use unowned only when the lifetime relationship is guaranteed. The example counter is sequential and would need isolation before concurrent use.
Swift closures, ARC and closure cycles, Swift concurrency and isolation
Related Questions
-
easy
-
medium
-
medium
-
hard