In Swift, a function can have default values for a parameter like this:
func init(name: String = "foo"){...}
Can a function with a completion handler have a default value so that when calling a function there is no need to specify the completionHandler as nil, similar to the below?
func foo(completion: (success: Bool) -> void = nil){...}
A completion handler in Swift is a function that calls back when a task completes. This is why it is also called a callback function. A callback function is passed as an argument into another function. When this function completes running a task, it executes the callback function.
The function declaration also contains a special keyword: @escaping. This means that the closure that's passed in as an argument for this parameter can escape the dataTask(with:completionHandler:) function. In other words, the closure is called after the function dataTask() finishes executing.
You can either do this:
func foo(completion: (success: Bool) -> Void = {_ in }) {
completion(success:true)
}
Or this:
func foo(completion: ((success: Bool) -> Void)? = nil) {
completion?(success:true)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With