简体   繁体   English

swift中不同类型的闭包语法 - 哪一个是正确的?

[英]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 方法1

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

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

Method 2 方法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 ? 或者是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 您可以从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 方法1: 定期关闭

Method 2: Trailing closure . 方法2: 尾随闭合 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. 如果第二个参数是completion ,并且animations参数将是最后一个,则尾随闭包将应用于动画等。因此它必须作为最后(或唯一)闭包参数。

If you miss a completion label, you are free to type it like this: 如果您错过了completion标签,您可以像这样输入:

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 . 为了完成你的问题:它是相同函数的相同实现 ,但语法不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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