Junior — Middle
Is it possible to use escaping closure with optional parameters?
sobes.tech AI
Answer from AI
Yes, in Swift, you can use escaping closures with optional parameters. Optional parameters in closures allow passing values that can be nil. This is useful, for example, when the result of an operation might be absent or unsuccessful.
Example of using an escaping closure with an optional parameter:
func fetchData(completion: @escaping (String?) -> Void) {
DispatchQueue.global().async {
let data: String? = "Request result" // or nil in case of error
completion(data)
}
}
fetchData { result in
if let data = result {
print("Received data: \(data)")
} else {
print("No data")
}
}
Here, completion is an escaping closure that accepts an optional String. This is a common pattern for asynchronous operations.