I\'m trying to create a function that grabs the category children\'s keys of a given user UID in Firebase, appends them to an array and then finally joins them together into one
observeSingleEvent(of:with:)
is an asynchronous operation, which means that it can return later after executing the function. That's why in your case you get always an empty String as return value
So in your case you can create a completion handler like this:
func fetchBuddyInfo(category: String, buddyId: String, completion: @escaping (String) -> ()) {
var buddyInterestsArray = [String]()
var buddyInterests = String()
referenceDatabase.child("Users").child(buddyId).child(category).observeSingleEvent(of: .value, with: { (categorySnap) in
for categoryItems in categorySnap.children.allObjects as! [FIRDataSnapshot] {
buddyInterestsArray.append(categoryItems.key)
}
buddyInterests = buddyInterestsArray.joined(separator: ",")
completion(buddyInterests)
})
}
And call your function like this:
fetchBuddyInfo(category: categoryString, buddyId: buddyId) { (buddyInfoString) in
// do whatever you want with your buddyInfoString
}