繁体   English   中英

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

[英]How to get an Array of Objects from Firestore in Swift?

在 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")
  }
}

我收到看起来像这样的数据


(
  {
    name = "Bob";
    age = 24;
  }
)

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

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

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

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

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

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

第二行可能有点长,但它可以防止每一个可能的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM