Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different types of closure syntax in swift - which one is correct?

I'm pretty curious which one of these syntax statements is (more) correct. Playground happily compiles both cases.

Method 1

// copied from SO and this appears clear to me
UIView.animate(
    withDuration: 3.0,
    animations: {

    },
    completion: { (Bool) in
        // completion code
    }
)

Method 2

UIView.animate(
    withDuration: 3.0,
    animations: {

        // code

    }) {(Bool) in
      // code when finished?
      // argument label completion missing?
    }

Why rounded brackets in 2nd method are closed before last argument stated? Or is that another implementation of UIView.animation?

like image 579
GiorgioE Avatar asked Dec 29 '25 00:12

GiorgioE


1 Answers

Both of them are correct.

  1. It is the usual closure syntax in a function call.

  2. It represents a Trailing closure.

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is written after the function call’s parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.

You can read more about trailing closures from https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

like image 186
PGDev Avatar answered Dec 30 '25 15:12

PGDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!