2016-10-27 8 views
0

変数を宣言してから、その値をUIAlertAction内に設定しようとしています。私はをタップすると、 "私はそこに行くのです"ボタンは、私の次のコードでは、出力は次のようになります。Swift:変数値をUIAlertAction内に設定する

1 thisCustomerRequesting:真

3 thisCustomerRequesting:偽

は、あなたが言うことができる私の理由「2 thisCustomerRequesting:....」が出力に表示されず、なぜ「3 thisCustomerRequesting:false」と表示されるのですか?は真であると思われますが、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)") 
+0

私のコンソールには2-3-1の順番があります。 – holex

答えて

1

出力2はコンソールにありますが、1 thisCustomerRequesting: trueを超えている必要があります。

出力3はthisCustomerRequestingがボタンを押したときに非同期でtrueに設定されるため、3 thisCustomerRequesting: falseと表示されます。
print("3 thisCustomerRequesting: \(thisCustomerRequesting)")が既に実行されています。

+0

はどこにでもあります。明らかなのは警告の補完ハンドラを使うことですが、if文ブロックが実行されていなくても実行されるはずのprint( "3 thisCustomerRequesting:..."を含む)コードを持っています。 – Kashif

+0

@Kashif関数内のコードをカプセル化します。それを両方の場所から呼び出します。 –

関連する問題