Sujay U N Sujay U N - 1 year ago 108
Swift Question

IOs Swift : How does completion closure work

Can anybody explain me, how does this code work

private func viewWillTransition(completion:(() -> Void)?)
if completion != nil

Answer Source

This is a basic scheme of implementing callbacks in Swift.

The function takes parameter completion of type () -> Void)?, meaning "an optional closure taking no parameters and not returning a value."

The code inside tests the optional value of closure for nil. If it is not nil, the code unwraps it with !, and makes a call.

A somewhat more idiomatic way of implementing this in Swift is with if let construct:

private func viewWillTransition(completion:(() -> Void)?) {
    if let nonEmptyCompletion = completion  {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download