swift - 将数据从 Firestore 存储到列表
问题描述
我有一个数据库,存储用户每天输入的一系列整数值并存储为整数列表。我有以下代码查询数据库并将搜索到的症状值存储到一个列表中,然后从函数中返回,而通过 for 循环返回的数据似乎包含数据库中的所有值但是当我print(returnedData)
只放置在查询之后和 return 语句之前,它会打印一个空列表。我不太确定为什么 for 循环没有正确附加到返回的数据列表中。
func yearDataReturn(year: Int,symptom: String)->[Int]{
//fetches all the year for the month and returns it as a list
let collectionRef = db.collection("entries")
var returnedData:[Int] = []
collectionRef.whereField("year", isEqualTo: year).whereField("UserID", isEqualTo: UserDefaults.standard.integer(forKey: "UserID")).order(by: "monthOfYear").order(by: "weekOfMonth").order(by: "dayOfMonth")
.getDocuments{(QuerySnapshot,err)in
for doc in QuerySnapshot!.documents{
let sympLis=doc.get("SymptomValues") as! [Int]
let symp=sympLis[self.symptoms.firstIndex(of: symptom)!]
returnedData.append(symp)
}
}
return returnedData
}
解决方案
首先欢迎来到本站。
这是一个异步调用,这意味着查询行的 ( collectionRef.whereField(...
) 块将在该return returnedData
行之后执行。
请查看这篇中型文章 ->在 Swift 中管理异步代码
您可以closure
像这样将 a 传递给您的函数->
func yearDataReturn(year: Int,symptom: String, completion: @escaping ([Int] -> Void)) {
//fetches all the year for the month and returns it as a list
let collectionRef = db.collection("entries")
var returnedData:[Int] = []
collectionRef.whereField("year", isEqualTo: year).whereField("UserID", isEqualTo: UserDefaults.standard.integer(forKey: "UserID")).order(by: "monthOfYear").order(by: "weekOfMonth").order(by: "dayOfMonth")
.getDocuments{(QuerySnapshot,err)in
for doc in QuerySnapshot!.documents{
let sympLis=doc.get("SymptomValues") as! [Int]
let symp=sympLis[self.symptoms.firstIndex(of: symptom)!]
returnedData.append(symp)
}
completion(returnedData)
}
}
用法
yearDataReturn(year: 5, symptom: "asdf") { symptomValues in
print(symptomValues)
}
推荐阅读
- javascript - Error 对象似乎如何在 Javascript 上自行创建属性?
- python - 有没有办法在组织中部署 python 桌面应用程序?
- python - AttributeError:“SnowflakeCursor”对象没有属性“光标”
- java - 尝试运行 Java Eclipse 项目时出错
- html - 用户在对话框外单击时如何调用该函数
- javascript - React 错误:使用 MaterialTable 重新渲染的次数过多
- webrtc - 建立连接后添加跟踪
- python - 尝试为我的模型找到最佳多项式回归次数时出现错误
- python - 连续删除其中一个按钮时如何“堆叠”按钮?蟒蛇,Tkinter
- python - 多处理代理:字母 getters 自己返回代理