Why does code not execute after alert response?

I am playing around and learning how to display an alert and I am seeing unexpected behavior


Based on the code snippet below, you can see there is a local variable defined as "result = false".

The alert message is displayed, which asks the user to enter "YES" or "NO"

When I click the "YES" button, I see "YES" text displayed, as expected in the handler

When I click the "NO" button, I see "NO" text displayed, as expected in the handler


Issue:

I never see the "print" in Line 19 displayed ever. What is going on please?


var result = false
let alert = UIAlertController(title: "Testing", message: "Hello", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "YES",
                              style: .destructive,
                              handler: { action in
                                            result = true
                                            print("YES")
                                       } ))

alert.addAction(UIAlertAction(title: "NO",
                              style: .cancel,
                              handler: { action in
                                            result = false
                                            print("NO")
                                       } ))

present(alert, animated: true, completion: nil)

print("result=\(result)")

Accepted Reply

That API is asynchronous. present() returns immediately, long before the alert is displayed or the user has tapped a choice. So you should be seeing your print statement output before the YES or NO.

Replies

That API is asynchronous. present() returns immediately, long before the alert is displayed or the user has tapped a choice. So you should be seeing your print statement output before the YES or NO.

I tested and get the alert and the print.


However, the print does not wait for the alert result, so when clicking Yes, I may get


result=false

YES


Which is normal because you return immediately from the alert.


Changing to:

present(alert, animated: true, completion: { print("result=\(result)") })

would not solve, because the completion handler is called after the

viewDidAppear(_:)
method is called on the presented view controller. (see present(_:animated:completion:) documentation).


To get it right, you could either use semaphore, to wait for the alert to return or to put the print in the handlers of IBAction.

Yes, the issue was that I am receiving the "result = xxxx" earlier . I lost it in the other print statements I have in my real code. Thanks for reminding me that the code is asynchronous