先看看 Swift 的 UIView
动画:
接口:
open class func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil)
调用:
UIView.animate(withDuration: 1, animations: {
}) { (finished) in
}
同样是 UIView
动画,看看别人 OC:
接口:
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^ __nullable)(BOOL finished))completion API_AVAILABLE(ios(4.0));
调用:
[UIView animateWithDuration:1 animations:^{
} completion:^(BOOL finished) {
}];
Swift 里 UIView
动画的 completion
标签直接被忽略了。
它不是针对谁,谁来都是一样,直接把你最后一个闭包的标签删掉。
不信自己写一个:
private func test(closure1: () -> Void, closure2: (String) -> Void) {
}
然后调用:
test(closure1: {
}) { (str) in
}
我表示这很蛋疼,因为有时候缺少参数标签已经影响代码的可读性了。
后面我了解到,之所以会变成这副逼样,是因为苹果强行给你安排了尾随闭包。

而破解之道也很简单,就是不接受它的安排,自己写:
test(closure1: {
}, closure2: { str in
print(str)
})

舒服了。
参考:
https://docs.swift.org/swift-book/LanguageGuide/Closures.html#ID102
网友评论