Q:

Swift -- How to create UIAlertView button click or response

first post here, so like the title says, I just created a UIAlertView which displays 2 buttons, one called yes and the other no. The UIAlertView appears when I click the exit button on my application. What I want to do is if i click the yes button, the app exits, if i click no, it stays. Here is the code for the exit button: Im stuck on the "if" part. Any help would be greatly appreciated! Thanks!
 @IBAction func Exit(sender: AnyObject) {
    let alert: UIAlertView = UIAlertView()
    alert.title = "Exit"
    alert.message = "Are you sure you want to exit?"
    let yesBut = alert.addButtonWithTitle("Yes")
    let noBut = alert.addButtonWithTitle("No")
    alert.show()

    if () {
        exit(0)
    }

}

A:

Two things:

You shouldn't exit from an app.  The user will hit the Home button when they are done with your app.  If you call exit(0), that is a crash as far as the user is concerned.
Alerts don't block.  Your if will happen before the user has had a chance to respond to your alert.  You need to make your ViewController a UIAlertViewDelegate:
class ViewController: UIViewController, UIAlertViewDelegate {

and implement alertView:clickedButtonAtIndex:.
@IBAction func exitButton(sender: AnyObject) {
    let alert: UIAlertView = UIAlertView()
    alert.title = "Exit"
    alert.message = "Are you sure you want to exit?"
    let yesBut = alert.addButtonWithTitle("Yes")
    let noBut = alert.addButtonWithTitle("No")
    alert.delegate = self  // set the delegate here
    alert.show()
    println("This line doesn't wait for the alert to be responded to.")
}

func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
    let buttonTitle = alertView.buttonTitleAtIndex(buttonIndex)
    println("\(buttonTitle) pressed")
    if buttonTitle == "Yes" {
        // This is not recommended behavior.  The user will interpret this as a crash.
        exit(0)
    }
}

Note: This is just for demonstration purposes.  It is not recommended to make code decisions based upon the button titles because this would break if your app was localized (translated to other languages).  Just use the buttonIndex in your if.

