Swift Closures
🧠 Swift Closures – Complete Beginner to Interview Guide (With Clear Examples)
Closures in Swift are self-contained blocks of code that you can store, pass, and execute later.
They are heavily used in iOS development, functional programming, callbacks, and async code.
1️⃣ What is a Closure in Swift? ⭐
A closure is like an anonymous function (function without a name).
Output
2️⃣ Why Closures Are Important ⭐
Closures are used for:
-
Callbacks (networking, animations)
-
Sorting & filtering
-
Async operations
-
Functional programming (
map,filter,reduce)
📌 Almost every real Swift app uses closures.
3️⃣ Basic Closure Syntax ⭐
4️⃣ Closure with Parameters ⭐
Output
5️⃣ Type Inference (Cleaner Syntax) ⭐⭐
Swift can infer types:
6️⃣ Shorthand Argument Names ($0, $1) ⭐⭐
7️⃣ Trailing Closures ⭐⭐⭐ (Very Important)
If a function’s last parameter is a closure, write it outside parentheses.
📌 Makes code clean and readable.
8️⃣ Closures as Function Parameters ⭐⭐⭐
Output
9️⃣ Capturing Values ⭐⭐⭐
Closures can capture variables from their surrounding scope.
Output
📌 Captured values persist between calls.
🔟 Escaping Closures ⭐⭐⭐ (Interview Favorite)
A closure escapes when it is executed after the function returns.
📌 Required for:
-
Async tasks
-
Stored closures
1️⃣1️⃣ Avoiding Retain Cycles ([weak self]) ⭐⭐⭐
❌ Problem
✅ Solution
📌 Prevents memory leaks.
1️⃣2️⃣ Closures with Collections ⭐⭐⭐
1️⃣3️⃣ Closure vs Function ⭐⭐
| Feature | Closure | Function |
|---|---|---|
| Name | Optional | Required |
| Inline use | ✅ | ❌ |
| Capture variables | ✅ | ❌ |
| Used as value | ✅ | Limited |
1️⃣4️⃣ Common Mistakes ❌
❌ Overusing shorthand syntax (hurts readability)
❌ Forgetting @escaping
❌ Retain cycles with self
❌ Using map for side effects
📌 Interview Questions (Swift Closures)
Q1. What is a closure?
👉 An anonymous function that can capture values
Q2. What is an escaping closure?
👉 Executed after function returns
Q3. Why use [weak self]?
👉 To avoid retain cycles
Q4. What is trailing closure syntax?
👉 Writing closure outside function call
✅ Summary
✔ Closures are anonymous functions
✔ Can capture surrounding variables
✔ Support shorthand & trailing syntax
✔ @escaping for async behavior
✔ [weak self] prevents memory leaks
✔ Essential for Swift & iOS interviews
