Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 603
Richard Reis Avatar asked Oct 24 '25 17:10

Richard Reis


1 Answers

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])
like image 190
Frank van Puffelen Avatar answered Oct 26 '25 07:10

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!