Function with optional completion block in Swift [duplicate]
Asked Answered
H

2

54

When I create a function, I can make a parameter optional by giving it a default value, like this:

func foo(bar: String = "foobar") {}

I want to do the same (make it optional) with a completion block. I have tried the following:

func foo(completionBlock: (foo: String) -> () = () -> ())
func foo(completionBlock: (foo: String) -> () = (foo: String) -> ())
func foo(completionBlock: (foo: String) -> () = ((foo: String) -> ()))
func foo(completionBlock: (foo: String) -> () = ((foo: String) in))
func foo(completionBlock: (foo: String) -> () = {(foo: String) in})

How can I do this?

EDIT:
This is/was a duplicate question, sorry for that. However, I couldn't find the solution in the original question. So nathan's answer is the best one

Highwrought answered 20/9, 2016 at 22:8 Comment(0)
A
55

In Swift 3:

func foo(completionBlock: (String) -> () = { _ in }) {}
Appolonia answered 20/9, 2016 at 22:12 Comment(1)
Wouldn't this need an @escaping for the completionBlock since it's implicitly non-escaping since Swift3.0?Arresting
M
82

If you want to default to nil:

func foo(completionBlock: ((String) -> ())? = nil) {

}

If your default completion block is very simple, you can put it right in the function's definition:

// A default completion block that is simple enough to fit on one line
func foo(completionBlock: (String) -> () = { result in print(result) }) {
    // ...
}

// A default completion block that does nothing
func foo(completionBlock: (String) -> () = {} ) {
    // ...
}

If your default completion block is more complex, you can define it as a separate function:

func defaultCompletion(result: String) {
    // ...
}

func foo(completionBlock: ((String) -> ()) = defaultCompletion) {

}
Mottled answered 20/9, 2016 at 22:12 Comment(2)
Where should I place the @escaping keyword in this case?Soileau
@Rao You don't have to. Optional closures are @escaping by default. Read more about it here.Ventricle
A
55

In Swift 3:

func foo(completionBlock: (String) -> () = { _ in }) {}
Appolonia answered 20/9, 2016 at 22:12 Comment(1)
Wouldn't this need an @escaping for the completionBlock since it's implicitly non-escaping since Swift3.0?Arresting

© 2022 - 2024 — McMap. All rights reserved.