callback の書き方
・クラス
final class ClosureAlert { class func showAlert(parentViewController: UIViewController, title: String, message: String, completion: ((Bool) -> Void)?) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) let yesAction = UIAlertAction(title: "見る", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) -> Void in // 引数にメソッドが使われてれば実行する if let completion = completion { // yesなのでtrue completion(true) } }) let noAction = UIAlertAction(title: "見ない", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) -> Void in // 引数にメソッドが使われてれば実行する if let completion = completion { // noなのでfalse completion(false) } }) alert.addAction(yesAction) alert.addAction(noAction) parentViewController.presentViewController(alert, animated: true, completion: nil) } }
・使い方
ClosureAlert.showAlert(self, title: "最新の記事", message: "注目です!", completion: { (isPositive) -> Void in if isPositive { // okの処理 } else { // ngの処理 } )