如何在异步函数中更改变量值?

时间:2020-02-03 23:37:04

标签: swift google-cloud-firestore

我正在尝试将数组的值设置为存储在我的Firebase Firestore中的一些东西。然后,我试图将阵列设置为UIPicker。请告诉我我的func声明出了什么问题:

func getDropDownOptions(completion: @escaping (_ in1: String,_ in2: String,_ in3: String,_ in4: String,_ in5: String) -> Void)

或我对功能的呼吁:

getDropDownOptions { (in1, in2, in3, in4, in5) in
            if in1 == "nil" {
                self.errorLabel.text = "Please add an intrest to your profile"
                return
            } else if in2 == "nil" {

                return self.sportPickerData = [in1, in2]
            } else if in3 == "nil" {

                return self.sportPickerData = [in1, in2, in3]
            } else if in4 == "nil" {
                return self.sportPickerData = [in1, in2, in3, in4]
            } else {
                return self.sportPickerData = [in1, in2, in3, in4, in5]
            }
        }

1 个答案:

答案 0 :(得分:1)

如果完成是在后台线程上调用的,那么您需要分派回主线程来更改UI。

// if you are in a background thread, then ...
DispatchQueue.main.async {
    // Update UI here
}

因此,对于错误标签,您绝对应该这样做。对于其他变量,您可以设置它们,但是如果它们导致UI更改,则可能应该在主线程中进行。

例如:

// if you are in a background thread, then ...
DispatchQueue.main.async {
    // Update UI here
    self.errorLabel.text = "Please add an intrest to your profile"
}