UIAlertControllerで表示したAlertもしくはActionSheetで、押されたボタンをインデックスで判断したい時は以下のようにすると良いでしょう。
let controller = UIAlertController(title: "アプリ開発言語",
message: "どの言語でアプリを開発してますか?",
preferredStyle: .actionSheet)
// ここでlet actions = controller.actionsにすると空の状態でhandler内で参照されるので注意
var actions = [UIAlertAction]()
let handler = { (action: UIAlertAction) in
// UIAlertController#actionsから押されたUIAlertActionのindexを得る
if let index = actions.index(of: action) {
print("index:\(index) title:\(action.title!)")
// 最後のボタンはキャンセル
if index == actions.count - 1 {
print("cancel")
}
}
}
controller.addAction(UIAlertAction(title: "Swift", style: .default, handler: handler))
controller.addAction(UIAlertAction(title: "Kotlin", style: .default, handler: handler))
controller.addAction(UIAlertAction(title: "Objective-C", style: .default, handler: handler))
controller.addAction(UIAlertAction(title: "Java", style: .default, handler: handler))
controller.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: handler))
// UIAlertActionを追加しきった後で代入すること
actions = controller.actions
present(controller, animated: true, completion: nil)
注意すべきは、handler関数でUIAlertControllerを参照すると、UIAlertControllerがUIAlertActionを経由してhandlerを参照するため循環参照になって、メモリリークすることです。(UIAlertControllerのdeinitが呼ばれません)。よって、handler内ではcontroller.actionsのように参照せずにactionsを参照しています。