Closure vs Completion Handler in Swift
Closures and completion handlers are closely related, but they serve different purposes in Swift development. Let’s break down the differences:

1. Closure
A closure is a self-contained block of code that can capture and store references to variables and functions from its surrounding scope.
Example of a Closure:
let greet = { (name: String) -> String in
return "Hello, \(name)!"
}
print(greet("Gati")) // Output: Hello, Gati!
πΉ Key Points:
✅ Closures can be stored, passed as parameters, and executed later.
✅ Used in higher-order functions like map
, filter
, and reduce
.
✅ Can capture values from their surrounding context.
2. Completion Handler
A completion handler is a special type of closure that is passed as a parameter to a function and is executed when an operation (like a network request or animation) is finished.
Example of a Completion Handler:
func fetchData(completion: (String) -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
completion("Data fetched successfully!")
}
}
fetchData { result in
print(result) // Output after 2 seconds: Data fetched successfully!
}
πΉ Key Points:
✅ Always used as a callback for asynchronous tasks.
✅ Allows functions to return results after the execution is complete.
✅ Helps avoid blocking the main thread.
π― Summary
- All completion handlers are closures, but not all closures are completion handlers.
- Closures are general-purpose and used in multiple scenarios.
- Completion handlers are specifically used to handle results from asynchronous tasks.
Let me know if you need further clarification! π
# iOS Interview Questions and Answers
# iOS Interview Preparation
Follow me on Linkedin: igatitech πππ
Comments
Post a Comment