5

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
  • 63
  • 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

37

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
  • 12,518
  • 6
  • 70
  • 114
Kametrixom
  • 14,225
  • 7
  • 44
  • 61