7

配列「listINeed」をハンドラ関数「handleConfirmPressed」に渡す方法はありますか? クラス変数として追加することでこれを行うことができましたが、それは非常にハックに思えたので、複数の変数に対してこれを行いたいので、より良い解決策が必要です。

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)))

カリー化された関数は次の省略形であることに注意してください。

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