Swift:在UIAlertAction中设置变量值



我正在声明一个变量,然后尝试在UIAlertAction中设置它的值。当我点击"我要去"按钮在我下面的代码输出是:

1 thiscustomerrequest: true

3 thiscustomerrequest: false

你能告诉我为什么行"2 thiscustomerrequest:.... "在输出中丢失,为什么"3 thiscustomerrequest:false "是假的,而我期望它是真的。

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)")

输出2应该在控制台,但在1 thisCustomerRequesting: true之上。

输出3表示3 thisCustomerRequesting: false,因为当用户按下按钮时,thisCustomerRequesting被异步设置为true
此时,print("3 thisCustomerRequesting: (thisCustomerRequesting)")已经执行。

最新更新