Chapter 75: Swift Closures

1. What is a closure? (the most honest, intuitive explanation)

A closure is a function without a name that can:

  • capture variables from the surrounding scope (even after that scope ends)
  • be passed around like any other value
  • be stored in variables, arrays, dictionaries…
  • be called later

In simple words:

A closure is an anonymous function that remembers the environment where it was created.

Think of a closure as a small portable worker that:

  • Knows its instructions (the code inside {})
  • Remembers who hired it and what tools it was given (captured variables)
  • Can be sent to another department (passed as parameter)
  • Can be called much later (even after the original room is closed)

2. The basic syntax — every form you will actually see

2.1 Simplest closure — no parameters, no return

Swift

2.2 Closure with parameters & return value

Swift

Shorthand syntax (very common & clean):

Swift

2.3 Trailing closure syntax (the most beautiful & most used style)

When the last parameter of a function is a closure, Swift lets you write it outside the parentheses — very clean.

Swift

You will see trailing closures everywhere in SwiftUI, Combine, animations, networking, etc.

3. Capturing values — the real superpower of closures

Closures can remember variables from the surrounding scope — even after that scope disappears.

This is called capturing or closing over variables.

Swift

Real-life analogy:

Think of a counter function as a ticket machine at a parking lot. Each time you call makeCounter(), you get a new independent machine — each remembers its own ticket count.

This is why closures are so powerful for:

  • callbacks
  • completion handlers
  • stateful operations
  • event handlers

4. Real-life examples — closures you will actually write every day

Example 1 – Completion handler (networking, animations, alerts)

Swift

Example 2 – Sorting with custom comparator (very frequent)

Swift

Example 3 – SwiftUI button action (very common)

Swift

Example 4 – Animation completion (very typical in SwiftUI/UIKit)

Swift

5. Very Common Beginner Mistakes & Correct Habits

Mistake Wrong / Dangerous code Correct / Better habit Why?
Forgetting @escaping on completion handlers func fetch(completion: (String) -> Void) func fetch(completion: @escaping (String) -> Void) Without @escaping you get compile error when storing the closure
Strong reference cycles (memory leak) self.button.action = { self.doSomething() } Use [weak self] or [unowned self] Retain cycle — view controller never deallocates
Using var inside closure when not needed var count = 0; closure = { count += 1 } let count = 0 if not changing let is safer
Long closure body without trailing syntax array.map({ item in … }) array.map { item in … } Trailing closure is much more readable
Mutating captured variable without var let counter = 0; increment = { counter += 1 } var counter = 0 Compile error — captured let cannot be mutated

6. Quick Summary — Closure patterns you will use every day

Goal Most idiomatic code Notes / Tip
Simple completion handler fetch { result in … } Trailing closure style
Capture self safely { [weak self] in self?.doSomething() } Prevents retain cycles
Sort with custom logic sorted { $0.price < $1.price } Very common
Animation / alert completion animate { … } completion: { finished in … } Trailing closure is standard
Map / filter / reduce chains array.filter { $0 > 10 }.map { $0 * 2 } Functional style — very idiomatic

7. Small Practice – Try these

  1. Create a function greetPeople(_ names: [String], greeting: String = “Namaste”) that uses forEach to print “Namaste, Rahul!” for each name.
  2. Write a closure that calculates discount: let applyDiscount = { (price: Double, percent: Double) -> Double in price * (1 – percent/100) }
  3. Create a retry function using closure: func retry(times: Int, delay: Double, operation: @escaping () -> Bool)

Paste your code here if you want feedback or want to see even cleaner versions!

What would you like to explore next?

  • @escaping closures in depth
  • Capturing values — strong, weak, unowned
  • Trailing closures in SwiftUI & Combine
  • Closure as function parameter vs function type
  • Escaping vs non-escaping closures
  • Or move to another topic (optionals, arrays, switch, protocols…)

Just tell me — we’ll continue in the same clear, patient, detailed style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *