闭包表达式(Closure Expressions)
最后更新于:2022-04-01 04:55:35
## 闭包表达式(Closure Expressions)
如果闭包表达式参数在参数列表中的最后一个时,使用尾部闭包表达式。给定闭包参数一个描述性的命名。
推荐做法:
~~~
UIView.animateWithDuration(1.0) {
self.myView.alpha = 0
}
UIView.animateWithDuration(1.0,
animations: {
self.myView.alpha = 0
},
completion: { finished in
self.myView.removeFromSuperview()
}
)
~~~
不推荐做法:
~~~
UIView.animateWithDuration(1.0, animations: {
self.myView.alpha = 0
})
UIView.animateWithDuration(1.0,
animations: {
self.myView.alpha = 0
}) { f in
self.myView.removeFromSuperview()
}
~~~
当单个闭包表达式上下文清晰时,使用隐式的返回值:
~~~
attendeeList.sort { a, b in
a > b
}
~~~