闭包表达式/Closure Expressions
Use trailing closure syntax only if there's a single closure expression parameter at the end of the argument list. Give the closure parameters descriptive names.
当参数列表的最后一个元素是闭包表达式,且整个参数列表里只有一个闭包参数的情况下,使用尾随闭包语法。给闭包参数定义一个描述性的命名。
推荐(Preferred):
UIView.animate(withDuration: 1.0) {
self.myView.alpha = 0
}
UIView.animate(withDuration: 1.0, animations: {
self.myView.alpha = 0
}, completion: { finished in
self.myView.removeFromSuperview()
})
不推荐(Not Preferred):
UIView.animate(withDuration: 1.0, animations: {
self.myView.alpha = 0
})
UIView.animate(withDuration: 1.0, animations: {
self.myView.alpha = 0
}) { f in
self.myView.removeFromSuperview()
}
For single-expression closures where the context is clear, use implicit returns:
对于上下文清晰的单独表达式闭包,使用隐式返回:
attendeeList.sort { a, b in
a > b
}
Chained methods using trailing closures should be clear and easy to read in context. Decisions on spacing, line breaks, and when to use named versus anonymous arguments is left to the discretion of the author. Examples:
在链式方法结合尾随闭包的使用场景中,应当保证代码清晰且可读性强。作者将自行抉择空格、换行、何时使用具名参数、何时使用匿名参数等问题。举例:
let value = numbers.map { $0 * 2 }.filter { $0 % 3 == 0 }.index(of: 90)
let value = numbers
.map {$0 * 2}
.filter {$0 > 50}
.map {$0 + 10}