This Question is not a duplicate.
So I have a simple function that will take a parameter of the index of what tableview cell was clicked so the function will go into the didSelectRowAt tableView function, and it will also return a String.
The Function is called getOpposingUserName and it connects to firebase to gather the information provided inside the database.
Now I know that the functionality of the function works it is sort of a logic error that I don't quite understand. From what I know is that whenever you try to get data from firebase it runs that code and takes a second to actually get the data. but as its doing that it keeps running the code below where you tried to get data from the database.
which means if I want to return a String then the string will always be nil or whatever I set its initial value to, because the database will take to long to load and the function will already have ran through the code to return something.(that's my understanding of it, I'm sure there is a way more technical way to explain it)
so basically what I am asking is how would I "load" the data into a variable first then check that firebase has indeed loaded something into the variable and then return the variable for whatever called the function
This question IS not a duplicate I have read the question and tried to make sense of it in my own implementation. I am not returning a function that code is confusing to me when I read it.
here is my code for the function
func getOpposingUsername(_ index: Int) -> String {
var opposingUser: String = ""
//the self.tieBetToUser just gets the randomized id from the bet in firebase don't need to worry about it
self.datRef.child("Bets").child(self.tieBetToUser[index]).observe(.childAdded, with: { snapshot in
guard let dict = snapshot.value as? [String: AnyHashable] else {
return
}
opposingUser = dict["OpposingUsername"] as! String
print(opposingUser) //this code actually never runs I found out
})
//sleep(4) this will not work and is actually bad code anyway different phones may be faster or slower
return opposingUser // will always return "" at the moment
}
here is the solution the internet has provided
typealias someting = (String?) -> Void
func getOpposingUsername(completionHandler: @escaping someting, _ index: Int) {
var opposingUser: String = ""
self.datRef.child("Bets").child(self.tieBetToUser[index]).observe(.childAdded, with: { snapshot in
guard let dict = snapshot.value as? [String: AnyHashable] else {
return
}
opposingUser = dict["OpposingUsername"] as! String
if opposingUser.isEmpty {
completionHandler(nil)
} else {
completionHandler(opposingUser)
}
})
}
How exactly would I call this function somewhere else? like getOpposingUsername(somethingGoesHere, index.path)