2016-10-27 3 views
0

변수를 선언하고 UIAlertAction 내에 값을 설정하려고합니다. 나는 을 탭하면 "내가 거기 갈거야" 버튼 내 아래 코드의 출력은 다음과 같습니다스위프트 : 변수 값을 UIAlertAction 내부로 설정합니다.

1 thisCustomerRequesting : 사실

3 thisCustomerRequesting : 거짓

당신이 말할 수 있습니까 이유 "2 thisCustomerRequesting : ...." 출력에 누락되었습니다. 왜 "3 thisCustomerRequesting : 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

주위에 어떤 방법이 있습니다. 분명한 것은 alert의 완료 핸들러를 사용하는 것이지만 if 문 블록이 실행되지 않아도 실행되어야하는 print ("3 thisCustomerRequesting : ...")를 포함하는 아래 코드가 있습니다 – Kashif

+0

@Kashif 함수에서 해당 코드를 캡슐화합니다. 두 곳에서 불러라. –

관련 문제