我正在使用Firestore(仍处于测试阶段),我的数据结构如下:
我想获取每个成分作为字符串,以创建具有其名称的成分类对象。这是我使用的方法:
private func loadIngredients(){
let db = Firestore.firestore()
let recipeCollectionRef = db.collection("dishes").document((recipe?.name)!)
recipeCollectionRef.getDocument { (document, error) in
if let document = document {
print("Document data: \(document.data())")
print("\(document.data().values)")
for value in document.data().values {
print("Value: \(value)")
print(type(of: value))
}
} else {
print("Document does not exist")
}
}
}
这目前产生:
文件数据:[“成分”:<__ NSArrayM 0x60000025f2f0>(香蕉,燕麦片),“水平”:简单] LazyMapCollection,Any>(_ base:[“ingredients”:<__ NSArrayM 0x60000065ad60>(香蕉,燕麦片),“水平”: easy],_ transnsform :( Function))值:(香蕉,燕麦片)__ NSArrayM值:easy NSTaggedPointerString
据我所知,基于阅读Apple关于字典的文档:我的字典有[String:Any]类型,在这种情况下,“ingredients”是作为键的字符串,值可以是任何对象。我正在使用的数组是一个Mutable数组。
关于如何获得该数组及其各自的元素,我感到非常困惑。我已经尝试从LazyMapCollection转换为String但是将整个数组作为字符串生成。我也尝试通过键“成分”访问该值,但这不起作用“不能下标LazyMapCollection<[String : Any], Any>
类型的值,其索引类型为String
正如你所说,document.data()
是一本字典([String:Any]
)。
所以从这开始:
if let document = document, let data = document.data() as? [String:Any] {
}
现在,如果您想访问配料阵列,您可以:
if let ingredients = data["ingredients"] as? [String] {
}
你得到的一切:
private func loadIngredients(){
let db = Firestore.firestore()
let recipeCollectionRef = db.collection("dishes").document((recipe?.name)!)
recipeCollectionRef.getDocument { (document, error) in
if let document = document, let data = document.data() as? [String:Any] {
// Get the ingredients array
if let ingredients = data["ingredients"] as? [String] {
// do whatever you need with the array
}
// Get the "easy" value
if let east = data["easy"] as? String {
}
} else {
print("Document or its data does not exist")
}
}