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

好久不见. 提交于 2020-08-20 02:18:27

问题


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

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

But the response I get is Value of type 'Any' has no subscripts

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


回答1:


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

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



回答2:


A better way of writing @Frank van Puffelen's answer would be:

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.



来源:https://stackoverflow.com/questions/55368369/how-to-get-an-array-of-objects-from-firestore-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!