Kashif Kashif - 1 month ago 6
Swift Question

Swift: Setting variable value inside UIAlertAction

I am declaring a variable, then trying to set its value inside UIAlertAction. When I tap the "I am going there" button In my below code the output is:


1 thisCustomerRequesting: true

3 thisCustomerRequesting: false


Can you tell my why line "2 thisCustomerRequesting: ...." is missing from output and why "3 thisCustomerRequesting: false" is false while i expect it to be true.

var thisCustomerRequesting = false
if thisCustomerRequesting == false {
let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "I am going there", style: .destructive, handler: {
(alertAction1: UIAlertAction) in
thisCustomerRequesting = true
print("1 thisCustomerRequesting: \(thisCustomerRequesting)")
}))
alert.addAction(UIAlertAction(title: "Close", style: .default,handler: nil))
self.present(alert, animated: true, completion: nil)
print("2 thisCustomerRequesting: \(thisCustomerRequesting)")
}
print("3 thisCustomerRequesting: \(thisCustomerRequesting)")

Answer

Output 2 should be in your console but above 1 thisCustomerRequesting: true.

Output 3 says 3 thisCustomerRequesting: false because thisCustomerRequesting gets set to true asynchronously when the user presses the button.
At that time print("3 thisCustomerRequesting: \(thisCustomerRequesting)") is already executed.

Comments