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

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 storedpassed as parameters, and executed later.
✅ Used in higher-order functions like mapfilter, and reduce.
✅ Can capture values from their surrounding context.

2. Completion Handler

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

Popular posts from this blog

30 Days of SwiftUI — Day 1: Getting Started with SwiftUI

30 Days of SwiftUI Learning Journey: From Zero to Hero!

30 Days of SwiftUI - Day 11: Building Interactive SwiftUI Apps