如何将更多参数传递给 UIAlertAction 的处理程序?

How do I pass more parameters to a UIAlertAction's handler?

有什么方法可以将数组 "listINeed" 传递给处理函数 "handleConfirmPressed" 吗?我可以通过将它添加为 class 变量来做到这一点,但这看起来很老套,现在我想对多个变量这样做,所以我需要一个更好的解决方案。

func someFunc(){
   //some stuff...
   let listINeed = [someObject]

   let alert = UIAlertController(title: "Are you sure?", message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)
   alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
   alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler: handleConfirmPressed))
   presentViewController(alert, animated: true, completion: nil)
}

func handleConfirmPressed(action: UIAlertAction){
  //need listINeed here
}

最简单的方法是将闭包传递给 UIAlertAction 构造函数:

func someFunc(){
    //some stuff...
    let listINeed = [ "myString" ]

    let alert = UIAlertController(title: "Are you sure?", message: "message", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
    alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler:{ action in
        // whatever else you need to do here
        print(listINeed)
    }))
    presentViewController(alert, animated: true, completion: nil)
}

如果你真的想隔离例程的功能部分,你总是可以只输入:

handleConfirmPressedAction(action:action, needed:listINeed)

进入回调块

一个稍微晦涩难懂的语法,在将函数传递给完成例程和回调函数本身时都保留了函数的感觉,就是将 handleConfirmPressed 定义为柯里化函数:

func handleConfirmPressed(listINeed:[String])(alertAction:UIAlertAction) -> (){
    print("listINeed: \(listINeed)")
}

然后您可以 addAction 使用:

alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler: handleConfirmPressed(listINeed)))

请注意,curried 函数是 shorthand for:

func handleConfirmPressed(listINeed:[String]) -> (alertAction:UIAlertAction) -> () {
    return { alertAction in
        print("listINeed: \(listINeed)")
    }
}