ntoonio ntoonio - 2 months ago 33
Swift Question

Function with optional completion block in Swift

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?

Answer

In Swift 3:

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