![](/img/trans.png)
[英]How to fix Swift warning in iOS "Multiple Closures with Trailing Closure Violation"
[英]iOS8 Trailing Closures in Swift
let callActionHandler = { (action:UIAlertAction!) -> Void) in
let alertMessage = UIAlertController(title: "Service Unavailable", message: "Sorry, the call feature is not available yet. Please retry later", preferredStyle: UIAlertControllerStyle.Alert)
alertMessage.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertMessage, animated: true, completion: nil)
};
// Code Snippet 1
let callAction = UIAlertAction(title: "Call" + "123-000-\(indexPath.row)", style: UIAlertActionStyle.Default ) { (action:UIAlertAction!) -> Void in
println("check this out")
}
// Code Snippet 2
let callAction = UIAlertAction(title: "Call" + "123-000-\(indexPath.row)", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) -> Void in
println("Lets check this out")
})
// Code Snippet 3
let callAction = UIAlertAction(title: "Call" + "123-000-\(indexPath.row)", style: UIAlertActionStyle.Default , handler: callActionHandler)
谢谢
您询问:
- Code Snippet 1和Code Snippet 2有什么区别?
代码片段1正在使用片段2的“尾随闭包”再现。请参阅The Swift Programming Language:Closures中的 Trailing Closure讨论,其中说:
如果需要将闭包表达式作为函数的最终参数传递给函数,并且闭包表达式很长,则将其写为尾随闭包可能很有用。 尾随闭包是一个闭包表达式,它写在它支持的函数调用的括号之外(和之后)
因此,代码片段1和代码段2正在做同样的事情。
- 哪个Snippet 1或Snippet 2更好的表示并应该使用?
通常,人们更喜欢片段1的尾随闭包语法,因为它更简洁。 但是使用任何使代码的意图既清晰又简洁的东西。
- Code Snippet 1到底意味着什么? 这是一种快速观察的财产(完成)吗?
不,它与代码段2完全相同。
- iOS8希望我们编写的方式显示在Snippet 1中,即当我在Xcode自动填充时按Enter键时,它会转换为Snippet 1.我们应该使用Code Snippet 1还是更喜欢使用Snippet 2/3,因为它们很容易被理解?
再次,使用你喜欢的任何东西,最清晰简洁。 通常,人们尽可能利用尾随闭包语法。
就个人而言,除了尾随闭包语法之外,我可以利用枚举的参数和点语法的推断类型来进一步简化:
let callAction = UIAlertAction(title: "Call 123-000-\(indexPath.row)", style: .default) { action in
print("check this out")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.