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.
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
}
}
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?
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
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments