![](/img/trans.png)
[英]How do I access the data from Cloud Firestore database in Firebase using Swift in Xcode?
[英]How do I store Firestore data in a variable that I can manipulate in Swift/Xcode?
假设我有一个名为 currentShells 的整数变量
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
let data = document.data()
currentShells = data!["Shells"]! as! Int
}
}
print(currentShells)
当我打印出变量时,我无法打印。 Swift 迫使我在查询前添加“self.currentShells”,但它不会因此更新变量。 如何从 Firestore 数据库中查询数据并快速使用它?
编辑:有关更多上下文,我想获取 currentShells 中的当前值(我想从我的 Firestore 中查询)并将固定整数添加到该数量并将其更新到我的数据库中
正如 Doug Stevenson 所说, getDocument是异步执行的。 这意味着
print(currentShells)
可以(并且大部分将)在之前执行
currentShells = data...
是。 将您的代码更改为
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
let data = document.data()
currentShells = data!["Shells"]! as! Int
print("after update: \(currentShells)")
}
}
print("probably before update: \(currentShells)")
应该打印您更新的数据。
建议
如果您不是 100% 确定设置了可选项并且是某种类型,则不应使用隐式解包。 这很容易导致崩溃! 使用guard
或if let
更安全:
if let data = data, let shells = data["Shells"] as? Int {
currentShells = shells
}
编辑
要使用 currentShells 的新值执行其他函数:
- 如果您需要在每次更新 currentShells 时执行相同的函数,请更新您的 var:
var currentShells: Int {
didSet {
yourFunc(currentShells)
}
}
- 否则,在调用函数更新 currentShell 时传递一个完成块:
func getShells(completion: @escaping ((Int) -> ())) {
...
docRef.getDocument { ...
if let document ... {
...
currentShells = ...
completion(currentShells)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.