我试图将我从Firebase数据库中读取的信息保存到一个变量中。这就是我阅读信息的方式:
dbHandle = dbReference?.child("users").child(userEmail!).child("state").observe(.value, with: { (snapshot) in
if let userState = (snapshot.value as? String){
var taxRate = self.stateAbbreviations[userState]!
print(taxRate)
}
})
我现在的问题是如何使userState&taxRate在调用之外可见?
我尝试在调用外部声明userState,在调用内部初始化它,然后再次在调用外部引用它,但它不起作用。例如:
var userState:String? = ""
dbHandle = dbReference?.child("users").child(userEmail!).child("state").observe(.value, with: { (snapshot) in
let userState = (snapshot.value as? String)
var taxRate = self.stateAbbreviations[userState]!
print(taxRate)
})
print(userState)
但它只会打印出来
有什么建议吗??
最佳答案
您正在将一个var userState
初始化为一个空字符串,并且您在完成之外的打印将检索它的默认值,在您的firebase完成中,您正在使用let userState =
初始化另一个userState变量
如果要在调用之外使用userState和taxRate,可以这样做,例如:
// Create your variables
var userState: String = “”
//Create a func with completion handler
func getUserStateAndTaxRate(completion:((String,String) -> Void)?) {
dbHandle = dbReference?.child("users").child(userEmail!).child("state").observe(.value, with: { (snapshot) in
let userState = (snapshot.value as? String)
var taxRate = self.stateAbbreviations[userState]!
print(taxRate)
completion?(userState, taxRate)
})
}
//Then call it
getUserStateAndTaxRate { (userState, taxRate) in
// userState and taxRate are now available
self.userState = userState
self.taxRate = taxRate
}
关于swift - 将Firebase快照分配给变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50204618/