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

时间:2016-08-05 03:29:34

标签: ios swift handler uialertcontroller

似乎有3种不同的方式来编写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

这些都是制作处理程序吗?有什么区别,最好用?

2 个答案:

答案 0 :(得分:2)

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

有关此内容的更多信息,请参阅Swift Programming Language一书,请参阅有关闭包的部分。

答案 1 :(得分:0)

一切都一样。由于swift是强类型语言,因此无需将操作定义为UIAlertAction,因为coz UIAlertAction的init方法将其定义为UIAlertAction。 就像在从该数组中检索值时使用某个自定义类定义数组时,您不需要像在Objective C中那样强制转换它。

所以以上3种方式中的任何一种都可以,3号看起来很清楚并且按照我的口味拍摄:)

此外,因为它没有返回类型,所以也不需要提及Void(返回类型)。如果它有返回类型,您需要提及param -> RetType in

method { param -> String in
        return "" // should return a String value
}
相关问题