0

This is my code:

func checkIfExist(property: String, isEqualTo: Any) -> Bool {
    let query = db.collection("users").whereField(property, isEqualTo: isEqualTo)
    query.getDocuments { (snapshot, error) in
        guard let snapshot = snapshot?.documents else { print(error!); return }
        print("There is \(snapshot.count) items.")
        if snapshot.count == 1 {
            return true
        } else {
            return false
        }
    }
}

Xcode is yelling errors and I understand why, but I don't know how to fix it. How do I return something in this case? Should I use a library like PromiseKit? Thanks.

3
  • Please post details of the errors you are getting Commented Dec 29, 2017 at 18:48
  • That I should have a return outside a closure... Commented Dec 29, 2017 at 18:48
  • Sorry my bad. Yes you can't have a return in a closure. Where would it return to as it could finish at any time and runs in the background. You function will finish straight after the call to getDocuments but that call may finish some time layer. You need to look into another method of handling that. Commented Dec 29, 2017 at 19:00

1 Answer 1

1

You don't. Async functions can't return a result on function return. You need to write your function to take a completion closure. Then call it and pass in the code that you want to execute when the async task is done in the completion closure. There are dozens and dozens of examples of this on this board. I've written a few sample projects that illustrate it.

Check this link, for example:

https://github.com/DuncanMC/Async_demo.git

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, you could use PromiseKit, or Futures, or one of those design patterns. They are other solutions to this problem, but the idea is the same (you provide one or more closures that gets called when the async task finishes, and that code handles the result of the task.)
Got it. I actually managed to make it work 1 min ago with PromiseKit. Success.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.