美文网首页
Swift | 函数的闭包参数标签被忽略的问题

Swift | 函数的闭包参数标签被忽略的问题

作者: 无夜之星辰 | 来源:发表于2020-06-16 20:29 被阅读0次

先看看 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

相关文章

网友评论

      本文标题:Swift | 函数的闭包参数标签被忽略的问题

      本文链接:https://www.haomeiwen.com/subject/egxztktx.html