I have this method to extract user data (from Firestore) into a custom UserModel Struct. But, it isn't returning the desired user data out of the function:
func getArtistProfileCardData(artistName: String) -> UserModel {
var retData: UserModel = UserModel(isArtist: false, first: "", last: "", artistName: "something", occupation: "", profileUrl: "", followers: 0)
let usersRef = db.collection("users")
usersRef.whereField("artistName", isEqualTo: artistName)
.getDocuments { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
do {
let data = try document.data(as: UserModel.self)
retData = data
// printing retData.artistName gives me correct output.
} catch _ {
print("Error getting document from querySnapshot.")
}
}
}
}
// printing retData.artistName gives me "something" which I initialized right in the beginning of this function.
return retData
}
IRC, the innermost closure should capture the retData
variable so I should be able to extract the data inside data
variable and return it out of the function. However, that isn't what's happening. Why is that so? And how would I go about achieving the desired effect?
Thank you.