100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Swift Closures Cheat Sheet

Swift Closures Cheat Sheet

Covers Swift closure syntax, trailing closures, capture semantics, and common functional patterns like map, filter, and reduce.

1 PageIntermediateApr 5, 2026

Closure Syntax

Basic closure declarations and shorthand argument names.

swift
// Basic closure syntaxlet greet: (String) -> String = { name in    return "Hello, \(name)!"}print(greet("Swift")) // Hello, Swift!// Shorthand argument nameslet add: (Int, Int) -> Int = { $0 + $1 }// No parameters, no return valuelet sayHi: () -> Void = {    print("Hi!")}

Trailing Closures

Passing closures as the final argument to a function.

swift
func fetchData(completion: (Data?) -> Void) {    // ... async work    completion(nil)}// Trailing closure syntaxfetchData { data in    print(data ?? "no data")}// Multiple trailing closures (Swift 5.3+)func animate(duration: Double, animations: () -> Void, completion: (Bool) -> Void) {    animations()    completion(true)}animate(duration: 0.3) {    view.alpha = 0} completion: { finished in    print("Done: \(finished)")}

Capture Semantics

How closures capture surrounding variables and self.

  • Capture list [self]- Explicitly captures variables at closure creation time, e.g. { [self] in ... }
  • [weak self]- Captures self as an Optional to avoid strong reference cycles: { [weak self] in guard let self else { return } }
  • [unowned self]- Captures self without optional wrapping; crashes if self is deallocated before the closure runs
  • @escaping- Marks a closure parameter that outlives the function call, e.g. stored as a property or called asynchronously
  • @autoclosure- Automatically wraps an expression argument in a closure, e.g. the condition in assert(condition:)
  • Value capture- Closures capture a reference to variables, not a copy — mutating a captured var inside affects the outer scope

Common Closure Patterns

Using closures with standard collection methods.

swift
let numbers = [5, 3, 8, 1]let doubled = numbers.map { $0 * 2 }          // [10, 6, 16, 2]let evens = numbers.filter { $0 % 2 == 0 }    // [8]let sum = numbers.reduce(0) { $0 + $1 }       // 17let sorted = numbers.sorted { $0 < $1 }       // [1, 3, 5, 8]// forEachnumbers.forEach { print($0) }
Pro Tip

Prefer [weak self] over [unowned self] in closures stored as properties (like completion handlers) — unowned crashes on deallocation, while weak degrades gracefully with optional binding.

Was this cheat sheet helpful?

Explore Topics

#SwiftClosures#SwiftClosuresCheatSheet#Programming#Intermediate#ClosureSyntax#TrailingClosures#CaptureSemantics#CommonClosurePatterns#Functions#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet