制作UIAlertAction的处理程序的正确方法

问题描述:

似乎有3种不同的方式来编写UIAlertAction的处理程序。每下方似乎做我希望他们同/预期的事情制作UIAlertAction的处理程序的正确方法

// 1. 
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) -> Void in 
    print("a") 
}) 

// 2. 
let okAction = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) in 
    print("b") 
}) 

// 3. 
let okAction = UIAlertAction(title: "OK", style: .Default) { (action) in 
    print("c") 
} 

// OUTPUT: 
// a 
// b 
// c 

难道这些都使处理程序?有什么区别,最适合使用?

+0

这个链接应该帮助http://stackoverflow.com/questions/24190277/writing-handler-for-uialertaction – gurmandeep

+0

@gurmandeep感谢。我仍然想明白为什么3.是最好的,他们之间的差异都是 – rdk

+0

我同意@Joey。更多详情请参阅https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertAction_Class/ – gurmandeep

它们都是一样的,它主要是你喜欢的句法风格问题。选项3使用类型推断和尾随闭包语法,因为它简洁并且在函数调用之外移动最后一个参数闭包时除去了多余的括号集,所以通常是首选。您可以通过删除action附近的括号来选择3,这些都不是必需的。

更多相关内容请参阅Swift Programming Language书中的说明,请参阅闭包一节。

其全部相同。由于swift是一种强类型语言,不需要将动作定义为UIAlertAction,因此的init方法将其定义为UIAlertAction。 就像当你从数组中检索值时定义一个数组的定制类一样,你不需要像在目标C中那样施放它。

因此,上述3种方法中的任何一种都可以,3号似乎是清晰的,为我的口味:)

也因为它没有返回类型没有必要提及Void(返回类型)了。如果它有一个返回类型,你需要一提的是像param -> RetType in

method { param -> String in 
     return "" // should return a String value 
}