gpt4 book ai didi

Swift 中的 iOS8 尾随闭包

转载 作者:搜寻专家 更新时间:2023-10-31 08:34:20 25 4
gpt4 key购买 nike

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)
  • 这里有 3 个代码片段,我的疑问是:
    1. 代码片段 1 和代码片段 2 有什么区别?
    2. Snippet 1 或 Snippet 2 中哪个表现更好,应该使用?
    3. 代码片段 1 的确切含义是什么?它是某种属性(完成)在 swift 中观察到的吗?
    4. iOS8 希望我们编写的方式显示在代码片段 1 中,即,当我在 Xcode 自动完成时按回车键时,它会转换为代码片段 1。我们应该使用代码片段 1 还是更喜欢使用代码片段 2/3,因为它们是容易理解吗?

谢谢

最佳答案

你问:

  1. What is the difference between Code Snippet 1 and Code Snippet 2 ?

代码片段 1 正在使用片段 2 的“尾随闭包”再现。请参阅 The Swift Programming Language: Closures 中的尾随闭包 讨论。 ,它说:

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is a closure expression that is written outside of (and after) the parentheses of the function call it supports

所以片段 1 和片段 2 做的事情完全一样。

  1. Which out of Snippet 1 or Snippet 2 is a better representation and should be used ?

通常人们会更喜欢代码段 1 的尾随闭包语法,因为它更简洁。但是,请使用使您的代码的意图既清晰又简洁的任何内容。

  1. What does Code Snippet 1 exactly mean? Is it some sort of property (completion) observing in swift?

不,它与片段 2 完全相同。

  1. The way iOS8 wants us to write is shown in Snippet 1, i.e., when I press enter while Xcode autocompletes, it gets converted to Snippet 1. Should we use Code Snippet 1 or still prefer using Snippet 2/3 as they are easily understood?

同样,使用您喜欢的任何内容,并且最简洁明了。通常,人们会尽可能地利用尾随闭包语法。


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

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

关于Swift 中的 iOS8 尾随闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26832219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com