-2

I would like to create a function with completion handler and I would like to make the handler so I can pass in nil.

func animate(completion: @escaping((Bool) -> ()) {
  //Do stuff
  completion(true)
}

I would like make the make the completion handler to be able to pass in nil when it's not needed, like:

animate(completion: nil)

It's not working & I get the error:

Nil is not compatible with expected argument type '(Bool?) -> ()

. Can you please help me how to do this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Hunor Gocz
  • 137
  • 12

1 Answers1

-1

Remove @escaping keyword and make closure optional by specifying default value. Note that this way optional closure de-facto remains escaping.

func animate(_ completion: ((Bool) -> ())? = nil) {
    //Do stuff
    completion?(true)
}

Possible usages:

animate({ value in
    print("Completion value: \(value)")
})
animate(nil)
animate() // pass nothing, because default value is nil

As trailing closure:

animate() { value in
    print("Completion value: \(value)")
}
Hexfire
  • 5,945
  • 8
  • 32
  • 42