如何在Swift中从Firestore获取对象数组?

如何在Swift中从Firestore获取对象数组?

问题描述:

在Swift中,要从Firestore检索数组,请使用:

In Swift, to retrieve an array from Firestore I use:

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;
  }
)

但是,如果我要单独检索名称,通常我会执行print(document.data()!["people"][0]["name"]).

However, if I were to retrieve the name alone, normally I'd do print(document.data()!["people"][0]["name"]).

但是我得到的响应是Value of type 'Any' has no subscripts

如何访问people数组中该对象内的名称键?

How do I access the name key inside that object inside the people array?

document.data()!["people"]返回的值是Any类型,您无法访问Any上的[0].

The value returned by document.data()!["people"] is of type Any and you can't access [0] on Any.

您首先需要将结果转换为数组,然后获取第一项.虽然我不是Swift专家,但应该是这样的:

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:

let people = document.data()!["people"]! as [Any]
print(people[0])