Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can swift functions have a default completion handler? [duplicate]

Tags:

ios

swift

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){...}
like image 479
Sean Avatar asked Jun 29 '16 17:06

Sean


People also ask

How does swift define completion handler?

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.

What does the @escaping keyword do when declaring a completion handler?

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.


1 Answers

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)
}
like image 59
Kametrixom Avatar answered Oct 26 '22 23:10

Kametrixom