[英]How to get an Array of Objects from Firestore in Swift?
In Swift, to retrieve an array from Firestore I use:在 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")
}
}
And I receive data that looks like this我收到看起来像这样的数据
(
{
name = "Bob";
age = 24;
}
)
However, if I were to retrieve the name alone, normally I'd do print(document.data()!["people"][0]["name"])
.但是,如果我要单独检索名称,通常我会执行print(document.data()!["people"][0]["name"])
。
But the response I get is Value of type 'Any' has no subscripts
但是我得到的响应是Value of type 'Any' has no subscripts
How do I access the name key inside that object inside the people
array?如何访问people
数组内该对象内的名称键?
The value returned by document.data()!["people"]
is of type Any
and you can't access [0]
on Any
. document.data()!["people"]
返回的值属于Any
类型,您无法访问Any
上的[0]
。
You'll first need to cast the result to an array, and then get the first item.您首先需要将结果转换为数组,然后获取第一项。 While I'm not a Swift expert, it should be something like this:虽然我不是 Swift 专家,但它应该是这样的:
let people = document.data()!["people"]! as [Any]
print(people[0])
A better way of writing @Frank van Puffelen's answer would be:写@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)
}
}
The second line may be a little long, but it guards against every error possible.第二行可能有点长,但它可以防止每一个可能的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.