Unexpected non-void return value in void function - Swift 4 (Firebase, Firestore)

Viewed 899

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?

3 Answers

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
    }
}

Your function should return Bool instead of String.

change function return type String to Bool

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
    }
}
Related