swift 中不同类型的闭包语法 - 哪一个是正确的?
Different types of closure syntax in swift - which one is correct?
我很好奇这些语法语句中哪一个(更)正确。
Playground 愉快地编译了这两种情况。
方法一
// copied from SO and this appears clear to me
UIView.animate(
withDuration: 3.0,
animations: {
},
completion: { (Bool) in
// completion code
}
)
方法二
UIView.animate(
withDuration: 3.0,
animations: {
// code
}) {(Bool) in
// code when finished?
// argument label completion missing?
}
为什么第二种方法中的圆括号在最后一个参数声明之前关闭?或者是 UIView.animation
的另一个实现?
两种方法的区别如下:
方法一:常规闭包
方法二:尾随闭包。
Last 函数签名中的闭包参数可以写成更短的语法。如果第二个参数是 completion
,而 animations
参数是最后一个,则尾随闭包将应用于动画等。
所以它必须作为最后一个(或唯一的)闭包参数。
如果您漏掉了 completion
标签,您可以这样输入:
UIView.animate(withDuration: 3.0, animations: {
}) {(completion: Bool) in
}
为了完成您的问题:它是相同功能的相同实现,但是不同的语法。
两个都是正确的
这是函数调用中常用的闭包语法。
表示一个尾随闭包。
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.
阅读更多关于尾随闭包的信息
我很好奇这些语法语句中哪一个(更)正确。 Playground 愉快地编译了这两种情况。
方法一
// copied from SO and this appears clear to me
UIView.animate(
withDuration: 3.0,
animations: {
},
completion: { (Bool) in
// completion code
}
)
方法二
UIView.animate(
withDuration: 3.0,
animations: {
// code
}) {(Bool) in
// code when finished?
// argument label completion missing?
}
为什么第二种方法中的圆括号在最后一个参数声明之前关闭?或者是 UIView.animation
的另一个实现?
两种方法的区别如下:
方法一:常规闭包
方法二:尾随闭包。
Last 函数签名中的闭包参数可以写成更短的语法。如果第二个参数是 completion
,而 animations
参数是最后一个,则尾随闭包将应用于动画等。
所以它必须作为最后一个(或唯一的)闭包参数。
如果您漏掉了 completion
标签,您可以这样输入:
UIView.animate(withDuration: 3.0, animations: {
}) {(completion: Bool) in
}
为了完成您的问题:它是相同功能的相同实现,但是不同的语法。
两个都是正确的
这是函数调用中常用的闭包语法。
表示一个尾随闭包。
阅读更多关于尾随闭包的信息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.