This question already has answers here:
Returning data from async call in Swift function
                                
                                    (12个答案)
                                
                        
                                29天前关闭。
            
                    
以下是打印“没有用户名的用户”,但将retVal打印为“ false”(我将功能更改为字符串只是为了进行故障排除,理想情况下应该是bool)我是新手,这绝对使我发疯。它正在重新分配retVal的代码块中,但没有重新分配它

static func isUserNameUnique(_ username : String) -> String {

    var retVal = "false"

    let db = Firestore.firestore()
    let newQuery = db.collection("users").whereField("userName", isEqualTo: username)
    newQuery.getDocuments { (document, error) in
        if document!.isEmpty {
            retVal = "true"
            print("No user with username")
        }
    }
    print("\(retVal)")
    return retVal
}


func validateFields() -> String? {

    //Check that all fields are filled in
    if premierCodeTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || userNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
        return "Please fill in all fields."
    }

    //Check unique username
    let cleanedUserName = userNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        Utilities.isUserNameUnique(cleanedUserName) { res in
        if !res {
            // return "please choose a unique username"
        }
    }

    return nil
}

最佳答案

您正在尝试使用异步方法同步返回一个值。

当您执行newQuery.getDocuments时,将继续执行而无需等待完成处理程序被调用。因此,在执行该行之后,将执行返回,然后调用完成处理程序。

如果要从异步方法获取值,则需要创建一个采用完成处理程序的方法,例如Khan给您的答案。

static func isUserNameUnique(_ username: String, completionHandler: @escaping (Bool) -> Void) {
    let db = Firestore.firestore()
    let newQuery = db.collection("users").whereField("userName", isEqualTo: username)
    newQuery.getDocuments { (document, error) in
       completionHandler(document!.isEmpty)
    }
}

关于ios - 在Swift中的if语句中重新分配值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59491242/

10-08 21:02