我正在使用 Swift 5、SwiftUI 和 Firebase 进行一个简单的项目,该项目循环遍历数组中的给定 id,在 Cloud Firestore 数据库中搜索每个 id,并将与该 id 关联的相应名称附加到新数组中。
例如,我得到一个数组的几个 id,然后对于给定数组中的每个元素,我获取与该 id 关联的文档,然后打印该文档中的“firstname”字段。
但是,我想将检索到的每个“名字”值存储到本地的单独数组中以备后用。在 Javascript 中,我知道这是使用 await 和 async 函数完成的,但是我在无数小时的故障排除中发现 Swift 没有 async 或 await。
这是我的代码:
func convertToNames(arr: [String]) -> [String]{
var newArr : [String] = []
for id in arr {
let docRef = db.collection("users").document(id)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
let data = document.get("firstname") ?? "nil"
print("gotten data: \(data)")
newArr.append(String(describing: …Run Code Online (Sandbox Code Playgroud)