I have the following query;
fileprivate func observeQuery() {
guard let query = query else { return }
stopObserving()
listener = query.addSnapshotListener({ [unowned self] (snapshot, error) in
guard let snapshot = snapshot else { return }
let models = snapshot.documents.map({ (document) -> Post in
if let model = Post(dictionary: document.data()) {
return model
} else {
print(error as Any)
}
}) //here
self.posts = models
self.documents = snapshot.documents
})
}
I am getting "Missing return in a closure expected to return 'Post'" mentioned as "//here" in the code. I have return model which is of type Post and I cannot access model after the closure. I have used the GitHub files here; Firestore GitHub iOS Quickstart
This error doesn't make sense to me can someone please shed some light on the matter?
Many thanks as always.
Your issue is that not all code branches return inside the closure of your map
statement. You should change map
to flatMap
, this way you can also get rid of the if statement by simply returning the failable initializer's result inside your closure, since flatMap
will filter out all nil
return values.
let models = snapshot.documents.flatMap({ document in Post(dictionary: document.data())})