Swift中的iOS8尾随闭包

4
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)
  • 这里有三个代码片段,我的疑问是:
    1. 代码片段1和代码片段2之间的区别是什么?
    2. 在代码片段1和代码片段2中,哪一个更好地表示并应该被使用?
    3. 代码片段1究竟是什么意思?它是Swift中的某种属性(完成)观察吗?
    4. iOS8希望我们按照代码片段1的方式编写,即当我在Xcode自动完成时按下回车键,它会转换为代码片段1。我们应该使用代码片段1还是仍然喜欢使用代码片段2/3,因为它们更容易理解?

谢谢

1个回答

4
你问道:

  1. 代码片段1和代码片段2之间有什么区别?

代码片段1使用了代码片段2的“尾随闭包”版本。请参见The Swift Programming Language: Closures中的“Trailing Closure”讨论,其中说:

如果您需要将一个闭包表达式作为函数的最后一个参数传递给函数,并且闭包表达式很长,则编写它作为尾随闭包可能很有用。 尾随闭包是在支持它的函数调用的括号外(并在括号后面)编写的闭包表达式。

因此,代码片段1和代码片段2完全相同。

  1. 代码片段1和代码片段2中的哪一个更好,应该使用哪一个?

通常情况下,人们更喜欢使用代码片段1的尾随闭包语法,因为它更简洁。但是你应该使用使你的代码意图清晰且简洁的语法。

  1. 代码片段1到底是什么意思?它是Swift中的某种属性(completion)观察?

不是的,它与代码片段2完全相同。

  1. iOS8希望我们使用的方式显示在代码片段1中,也就是说,当我按回车键时,Xcode自动完成时,它会转换为代码片段1。我们应该使用代码片段1还是仍然更喜欢使用容易理解的代码片段2/3?

同样,使用最清晰且最简洁的语法即可。通常情况下,人们在可能时使用尾随闭包语法。


个人而言,在尾随闭包语法之外,我可能会使用参数的推断类型和枚举的点语法来进一步简化:

let callAction = UIAlertAction(title: "Call 123-000-\(indexPath.row)", style: .default) { action in
    print("check this out")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接