我一直在尝试创建一个带有处理程序的UIAlertAtion
。我阅读了这个问题的答案,知道如何做。
我的问题只涉及其中的闭包部分。
1) 我知道可以写:{alert in println("Foo")}
或者{_ in println("Foo")}
,但是我不能写{println("Foo")}
。在这里的评论中解释了这是因为你需要处理参数操作。
这是否意味着,由于处理程序的类型是(UIAlertAction) -> Void)
,我必须始终捕获传递的alertAction?
2)
我也阅读了这个,答案基本上是说您可以将函数作为参数传递,但是该函数应该接受类型为UIAlertAction -> Void
的内容,我写了:
private func anything(action : UIAlertAction) {
print("hello")
}
然后我将我的alertaction编写为如下:
let anotherAction = UIAlertAction(title: "hi", style: UIAlertActionStyle.Default,
handler: anything(action)) // error: Use of unresolved identifier 'action'
我不明白为什么会出现这个错误。
3) 在评论中还提到:但是除此之外,在swift中你不需要写UIAlertActionStyle.Default。.Default也可以工作
我尝试着不使用样式,以便默认为.Default
let sendLogAction = UIAlertAction(title: "Log") { action in print("goodbye")}
但是我遇到了以下错误:
'(title: String, (_) -> ())'(也就是 '(title: String, _ -> ())')无法转换为 '(title: String?, style: UIAlertActionStyle, handler: ((UIAlertAction) -> Void)?)'(也就是 '(title: Optional, style: UIAlertActionStyle, handler: Optional ()>)),元组的元素数量不同
4)
同时阅读这个答案。我不明白为什么我们需要传递 alert
,这没有意义。好像我们已经定义了它的类型,我们不知道 alert 的类型是什么吗?!有人能解释一下在一般情况下传递操作本身会有什么用处吗?我的意思是我们能做些什么?
我知道这写成了 4 个问题,但我认为这实际上只是一个基础性问题。我在工程中广泛地阅读、使用闭包/完成处理程序,并在 playground 中进行了测试,但我仍然感到困惑。
alert
? - rmaddyswitch action.style
... 他正在切换警报,但他不是已经定义了:style: .Default
吗? - mfaanialert
。他正在切换action.style
。无论如何,那个 switch 语句只是一个例子。但这毫无意义。在实际代码中,没有人会这样做,因为你已经知道你设置了什么样式。 - rmaddyaction in
,有时候是alert in
,但它们并没有任何区别...还是没有意义。所以对于我的第4个问题,我想要一个很好的例子来展示被捕获的action
的用途。 - mfaani