0

I'm new to Swift object oriented dev in general. I'm trying to load the query results from Firebase into a ViewController. I'm struggling with get the QuerySnapShot into an object to be used as the source for the View Controller. Specifically, I keep getting a "Unexpected non-void return value in void function" error where the return statement is. Any ideas? It there's a better way to do this in general please let me know. Any help is much appreciated.

// MARK: - API

func getBoxContents() -> Dictionary<String, Any> {
    // Get user data to populate collection view
    let userRef = db.collection("documents")
    var userData: Array<Dictionary<String,Any>> = []

    userRef.whereField("email", isEqualTo: userEmail!).getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                var userData = document.data()
                print("\(document.documentID) => \(document.data())")
            }
            return userData
        }
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Your `return userData` is trying to return a value out of the closure it runs in, which is not possible. Since `getDocument()` runs asynchronously, you can't `return` any results from the database out of `getBoxContents`. Instead you'll want to pass in your own closure/completion handler, similar to the `{ (querySnapshot, err) in` that `getDocuments()` takes as a parameter. See for an example: https://stackoverflow.com/q/38469648/209103 – Frank van Puffelen Apr 24 '20 at 02:12
  • Thank you @FrankvanPuffelen, that was the issue and it lead me to do some more reading on Completion handlers and initializing objects. Thanks again! – Ben Robbins Apr 24 '20 at 17:10
  • Great to her that you got it working Ben! I closed your question against the one I linked earlier. – Frank van Puffelen Apr 24 '20 at 19:24
  • One more question more related to how to use this message board. Should I have closed the question as answered? I looked for a way to do it but couldn't find anywhere to. – Ben Robbins Apr 25 '20 at 14:11
  • You could have posted your solution as an answer. But since you didn't post an answer and it sounds like you implemented what's in the answer I linked, I closed it as a duplicate. – Frank van Puffelen Apr 25 '20 at 14:42

0 Answers0