Reputation: 67
I'm trying yo access a variable outside a function, I tried to declare the variable outside the class but it keeps displaying the initial value in the declaration not the value inside the function, here is my code, I need to access databaseScore
func getDatabaseScore()-> Int{
let ref2 = FIRDatabase.database().reference().child("users").child("user").child((user?.uid)!)
ref2.observeSingleEvent(of: .childAdded, with: { (snapshot) in
if var userDict = snapshot.value as? [String:Int] {
//Do not cast print it directly may be score is Int not string
var databaseScore = userDict["score"]
}
})
return databaseScore
}
Upvotes: 0
Views: 919
Reputation: 285082
As mentioned in the comment it's impossible to return something form a method containing an asynchronous task.
You need a completion block for example
func getDatabaseScore(completion: (Int?)->()) {
let ref2 = FIRDatabase.database().reference().child("users").child("user").child((user?.uid)!)
ref2.observeSingleEvent(of: .childAdded, with: { (snapshot) in
if let userDict = snapshot.value as? [String:Int] {
//Do not cast print it directly may be score is Int not string
completion(userDict["score"])
}
completion(nil)
})
}
getDatabaseScore() { score in
guard let score = score else { return }
// do something with unwrapped "score"
}
Upvotes: 1
Reputation: 53121
You're doing an async operation so getDatabaseScore
returns before observeSingleEvent
completes. You could look at something like this…
class MyClass {
var databaseScore: Int = 0
func getDatabaseScore() {
let ref2 = FIRDatabase.database().reference().child("users").child("user").child((user?.uid)!)
ref2.observeSingleEvent(of: .childAdded, with: { (snapshot) in
if let userDict = snapshot.value as? [String:Int] {
print(userDict["score"]) // Confirm you have the a value
self.databaseScore = userDict["score"]
}
}
}
Upvotes: 1