我在iOS 8中可以正常使用以下功能:

func showConfirmBox(msg:String, title:String,
    firstBtnStr:String,
    secondBtnStr:String,
    caller:UIViewController) {
        let userPopUp = UIAlertController(title:title,
            message:msg, preferredStyle:UIAlertControllerStyle.Alert)
        userPopUp.addAction(UIAlertAction(title:firstBtnStr, style:UIAlertActionStyle.Default,
            handler:{action in}))
        userPopUp.addAction(UIAlertAction(title:secondBtnStr, style:UIAlertActionStyle.Default,
            handler:{action in}))
        caller.presentViewController(userPopUp, animated: true, completion: nil)
}

我想进行如下操作,以便将要触摸一个或另一个按钮时要执行的方法作为参数传递:
func showConfirmBox(msg:String, title:String,
    firstBtnStr:String, firstSelector:Selector,
    secondBtnStr:String, secondSelector:Selector,
    caller:UIViewController) {
        let userPopUp = UIAlertController(title:title,
            message:msg, preferredStyle:UIAlertControllerStyle.Alert)
        userPopUp.addAction(UIAlertAction(title:firstBtnStr, style:UIAlertActionStyle.Default,
            handler:{action in caller.firstSelector()}))
        userPopUp.addAction(UIAlertAction(title:secondBtnStr, style:UIAlertActionStyle.Default,
            handler:{action in caller.secondSelector()}))
        caller.presentViewController(userPopUp, animated: true, completion: nil)
}

显然,我没有对firstSelector和secondSelector做正确的事情,因为到目前为止我尝试过的工作没有用。我想我没有为我想要的使用正确的语法,但是我确信可以做自己想做的事情。对正确执行方法有任何想法吗?

最佳答案

您的问题的单字答案是Closures

闭包的默认语法是() -> ()
除了选择器,您可以直接提及方法定义

func showConfirmBox(msg:String, title:String,
    firstBtnStr:String, firstSelector:(sampleParameter: String) -> returntype,
    secondBtnStr:String, secondSelector:() -> returntype,
    caller:UIViewController) {
    //Your Code
}

但是使用它会产生可读性问题,所以我建议您使用typeAlias
typealias MethodHandler1 = (sampleParameter : String)  -> Void
typealias MethodHandler2 = ()  -> Void

func showConfirmBox(msg:String, title:String,
                    firstBtnStr:String, firstSelector:MethodHandler1,
                    secondBtnStr:String, secondSelector:MethodHandler2) {

    // After any asynchronous call
    // Call any of your closures based on your logic like this
    firstSelector("FirstButtonString")
    secondSelector()
}

您可以像这样调用您的方法
func anyMethod() {
   //Some other logic

   showConfirmBox(msg: "msg", title: "title", firstBtnStr: "btnString",
         firstSelector: { (firstSelectorString) in
              print(firstSelectorString) //this prints FirstButtonString
         },
         secondBtnStr: "btnstring") {
           //Invocation comes here after secondSelector is called

         }
}

10-08 16:56