Swift:在UIAlertAction中设置变量值

时间:2016-10-27 14:54:03

标签: swift uialertcontroller uialertaction

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

  

1 thisCustomerRequesting:true

     

3 thisCustomerRequesting:false

你能告诉我为什么行" 2 thisCustomerRequesting:...." 在输出中缺失,为什么" 3 thisCustomerRequesting:false&#34 ; 是假的,而我希望它是真的。

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

1 个答案:

答案 0 :(得分:1)

输出2应位于您的控制台中,但应高于1 thisCustomerRequesting: true

输出3显示3 thisCustomerRequesting: false,因为thisCustomerRequesting在用户按下按钮时异步设置为true
那时print("3 thisCustomerRequesting: \(thisCustomerRequesting)")已经执行。