我正在尝试将我正在从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)
但它只打印出""
有什么建议吗?
答案 0 :(得分:1)
您正在将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
}