所以我想要一个布尔函数,它根据 users 集合中的用户是否存在给定的电子邮件来返回 true 或 false.
So I want a Boolean function that returns true or false depending on whether the given email exists for a user in the users collection.
但是,如果我尝试在 getDocuments 调用中返回 True 或 False,我会收到错误:non-void return value在 void 函数中
However if I try and return True or False within the getDocuments call I get the error: non-void return value in void function
func checkUserWith(email: String) -> Bool { let usersDB = database.collection("users") usersDB.whereField("email", isEqualTo: email).getDocuments { (snapshot, error) in if error != nil { print("Error: (error?.localizedDescription ?? "")") return false } for document in (snapshot?.documents)! { if document.data()["email"]! as! String == email { return true } } return false } }我有一种感觉,这是因为我试图在 Firestore 调用中返回一个布尔值,该布尔值需要不同的变量类型?
I have a feeling it is because I am trying to return a boolean within the Firestore call which is expecting a different variable type?
推荐答案由于 firebase 操作给你一个回调闭包,而且调用是异步的,我相信你不可能直接从闭包返回.但是,您可以按如下方式返回一个指示 true 或 false 的转义闭包...
Since the firebase operation gives you a callback closure, and the calls made asynchronously, I believe it wont be possible for you to directly return from closures. However, you can return an escaping closure indicating true or false as follows...
func checkUserWith(email: String, completion: @escaping (Bool) -> Void) { let usersDB = database.collection("users") usersDB.whereField("email", isEqualTo: email).getDocuments { (snapshot, error) in if error != nil { print("Error: (error?.localizedDescription ?? "")") completion(false) } for document in (snapshot?.documents)! { if document.data()["email"]! as! String == email { completion(true) return } } completion(false) } }然后当你调用这个方法时:
Then when you call this method:
checkUserWith(email: emailHere) { (isSucceeded) in if isSucceeded { //it exists, do something } else { //user does not exist, do something else } }更多推荐
void 函数中出现意外的非空返回值
发布评论