如何在Swift中从Firestore获取对象数组? [英] How to get an Array of Objects from Firestore in Swift?

查看:151
本文介绍了如何在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])

这篇关于如何在Swift中从Firestore获取对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆