简体   繁体   中英

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 ?

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

The difference between both methods is following:

Method 1: Regular closure

Method 2: Trailing closure . Last closure parameter in the signature of a function can be written in shorter syntax . If the second parameter would be completion , and animations parameter would be the last, the trailing closure would apply to animations etc. So it has to stand as the last (or the only) closure parameter.

If you miss a completion label, you are free to type it like this:

UIView.animate(withDuration: 3.0, animations: {

 }) {(completion: Bool) in

 }

For completion of your question as well: It is the same implementation of an identical function, but a different syntax .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM