7

有没有办法将数组“listINeed”传递给处理函数“handleConfirmPressed”?我可以通过将它添加为类变量来做到这一点,但这看起来很hacky,现在我想为多个变量执行此操作,所以我需要一个更好的解决方案。

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
}
4

1 回答 1

22

最简单的方法是将闭包传递给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 函数是以下内容的简写:

func handleConfirmPressed(listINeed:[String]) -> (alertAction:UIAlertAction) -> () {
    return { alertAction in
        print("listINeed: \(listINeed)")
    }
}
于 2016-01-26T02:14:26.337 回答