Search code examples
swiftswift2closurescompletion

IOs Swift : How does completion closure work


Can anybody explain me, how does this code work

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

Solution

  • 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  {
            nonEmptyCompletion()
        }
    }