【问题标题】:Right way to make a UIAlertAction's handler制作 UIAlertAction 处理程序的正确方法
【发布时间】:2016-08-05 03:29:34
【问题描述】:

似乎有 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

这些都是处理程序吗?有什么区别,哪一种最好用?

【问题讨论】:

标签: ios swift handler uialertcontroller


【解决方案1】:

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

Swift Programming Language 书中对此进行了详细说明,请参阅闭包部分。

【讨论】:

    【解决方案2】:

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

    所以以上 3 种方法中的任何一种都可以,第 3 种方法看起来很清晰,适合我的口味:)

    另外,由于它没有返回类型,因此也无需提及 Void(返回类型)。如果它有返回类型,则需要提及 param -> RetType in

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-12
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      相关资源
      最近更新 更多