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.

Kira
  • 1,575
  • 4
  • 26
  • 48
  • Please post details of the errors you are getting – Upholder Of Truth Dec 29 '17 at 18:48
  • That I should have a return outside a closure... – Kira Dec 29 '17 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. – Upholder Of Truth Dec 29 '17 at 19:00

1 Answers1

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

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • 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.) – Duncan C Dec 29 '17 at 19:31
  • Got it. I actually managed to make it work 1 min ago with PromiseKit. Success. – Kira Dec 29 '17 at 19:32