6

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){...}
Sean
  • 73
  • 1
  • 4
  • Do you want the default to be nil, or do you want the default to be some particular completion handler? – matt Jun 29 '16 at 17:32

1 Answers1

38

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)
}
Ryan Heitner
  • 13,119
  • 6
  • 77
  • 119
Kametrixom
  • 14,673
  • 7
  • 45
  • 62