Ios 如何在Swift中从Firestore获取对象数组?
在Swift中,要从Firestore检索数组,我使用:Ios 如何在Swift中从Firestore获取对象数组?,ios,swift,firebase,google-cloud-firestore,Ios,Swift,Firebase,Google Cloud Firestore,在Swift中,要从Firestore检索数组,我使用: currentDocument.getDocument { (document, error) in if let document = document, document.exists { let people = document.data()!["people"] print(people!) } else { print("Document does not exist") } } 我收到
currentDocument.getDocument { (document, error) in
if let document = document, document.exists {
let people = document.data()!["people"]
print(people!)
} else {
print("Document does not exist")
}
}
我收到的数据如下所示
(
{
name = "Bob";
age = 24;
}
)
但是,如果要单独检索名称,通常我会打印(document.data()![“people”][0][“name”])
但是我得到的响应是,类型为'Any'的值没有下标
如何访问
people
数组中该对象内的name键?由document.data()返回的值![“人”]
属于Any
类型,您无法在Any
上访问[0]
首先需要将结果强制转换为数组,然后获取第一项。虽然我不是一个敏捷的专家,但应该是这样的:
let people = document.data()!["people"]! as [Any]
print(people[0])
写@Frank van Puffelen答案的更好方法是:
currentDocument.getDocument { document, error in
guard error == nil, let document = document, document.exists, let people = document.get("people") as? [Any] else { return }
print(people)
}
}
第二行可能有点长,但它可以防止所有可能出现的错误。这使应用程序崩溃,并给了我这个错误
无法将“\u NSArrayM”类型的值转换为“NSDictionary”
你知道如何解决它吗?是的,我想我不小心把它变成了字典。我更新了我的答案,但我肯定也会建议搜索这些错误消息(因为这就是我正在做的)!非常感谢。我确实查找了这些错误消息,但有时不理解它们。例如,您的解决方案为我提供了人员[0]
结果。但是当我尝试获取人[0][“name”]
时,它告诉我不能用类型为“String”的索引下标“[Any]”类型的值
,因此我尝试将[Any]
转换为[Any:String]
,但我得到的类型“Any”不符合协议“Hashable”
。。。这就是我被卡住的原因…people[0]
是一个字典,其中每个键都是字符串,值是任何类型的(因为它可以是字符串和数字)。因此,people[0]作为[String:Any]
是正确的转换。