【发布时间】:2016-11-30 16:48:44
【问题描述】:
我一直在尝试创建一个UIAlertAtion,它也有一个处理程序。我阅读了this问题的答案并且知道该怎么做。
我的问题只是关于它的关闭部分。
1) 我知道我可以写:{alert in println("Foo")} 或 {_ in println("Foo")},但我不能写 {println("Foo")}。在 cmets here 中进行了解释,因为 您需要处理参数操作。
这是否意味着由于处理程序的类型为(UIAlertAction) -> Void)?,我必须始终捕获传递的alertAction?
2)
我还阅读了this,答案基本上是说您可以传入一个函数作为参数,但该函数应该采用UIAlertAction -> Void 类型的东西,我写道:
private func anything(action : UIAlertAction) {
print("hello")
}
然后这样写我的警报操作:
let anotherAction = UIAlertAction(title: "hi", style: UIAlertActionStyle.Default,
handler: anything(action)) // error: Use of unresolved identifier 'action'
我为什么会收到这个错误感到困惑
3) 在 cmets 中它还说:但除此之外,您不必快速编写 UIAlertActionStyle.Default。 .Default 也有效
我尝试不使用该样式进行写作,因此默认为.Default
let sendLogAction = UIAlertAction(title: "Log") { action in print("goodbye")}
然后我收到以下错误:
'(title: String, (_) -> ())' (aka '(title: String, _ -> ())') 不是 可转换为 '(title: String?, style: UIAlertActionStyle, handler: ((UIAlertAction) -> Void)?)' (aka '(title: Optional, style: UIAlertActionStyle,处理程序:可选 ()>)'),元组 有不同数量的元素
4)
还阅读this 答案。我不明白为什么我们需要传入alert 这没有任何意义。并不是不知道 alert 的类型是什么……我们不是已经定义了它的类型了吗?!!谁能解释一下传递动作本身通常在哪里有用,我的意思是我们可以用它做什么?
我知道这是写成 4 个问题,但我认为这实际上只是一个基础问题。我有广泛的read,在我正在操场上工作和玩耍的项目中使用了闭包/完成处理程序,但我仍然感到困惑。
【问题讨论】:
-
#4 没有意义。你指的是什么
alert? -
@rmaddy
switch action.style...他正在切换警报,但他还没有定义:style: .Default -
他没有切换
alert。他正在切换action.style。无论哪种方式,该 switch 语句只是一个示例。但这毫无意义。没有人会在真正的代码中这样做,因为你已经知道你设置了什么样式。 -
@rmaddy 是的,我用错了词,因为有时我看到人们写
action in有时alert in没有区别......但毫无意义。所以对于我的 4 号,我要求提供一个很好的例子来说明捕获的action的使用位置。
标签: swift closures uialertaction