Back to Swift Reference
🔶 Swift LanguageIntermediateSwift 1.0+

Closures & Capture Lists

Pass behavior as values, use trailing closure syntax, and avoid retain cycles with [weak self].

Closures are self-contained blocks of code you can pass around. Swift offers shorthand arguments ($0) and trailing closure syntax for readability.

An escaping closure that captures self strongly inside a class can create a retain cycle. Use [weak self] when the closure is stored by the object it captures.

closures.swift
1let names = ["Ada", "Linus", "Grace"]
2let sorted = names.sorted { $0.count < $1.count }
3
4final class Downloader {
5    var onFinish: (() -> Void)?
6    var status = "idle"
7
8    func start() {
9        onFinish = { [weak self] in
10            self?.status = "done"
11        }
12    }
13}

Common pitfalls

  • Structs cannot form retain cycles — [weak self] is only needed for reference types.
  • In async code, prefer structured concurrency (async/await) over completion-handler closures.

Still unclear? Ask BeeAI about Closures & Capture Lists.

Get a tailored explanation, or paste your own code for a Swift 6 review. Free members get daily questions — Pro is unlimited.

Ask BeeAI

Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.

See Pro Plans