2015-11-15 1 views
14

のパラメータとして関数を渡す:は、私が期待するように私は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で正しいことをやっておりません:1またはボタンの他​​にタッチしようとしているときに実行。私は私が望むものに対して正しい構文を使用していないと思いますが、私がしたいことをすることは可能です。適切にそれを行う方法の任意のアイデア?

+0

のようなあなたのメソッドを呼び出すことができますか?より具体的な情報を提供してください。 –

+0

私が意味するのは、コンパイラからエラーメッセージが出るということです。それが有用であれば、それらを含めることができます。むしろ、私は2番目の関数の構文が間違っていると思います。 – Michel

+0

私は他の方法(例えばジェネリックを使って)を見つけるために自分で努力していますが、この時点ではまだ成功していません。 – Michel

答えて

29
あなたの質問のための

1ワードの答えはClosures

閉鎖のデフォルトの構文を使用して、直接法のdefnition

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 

     } 
} 
関連する問題