4

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?

2 Answers 2

8

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])
Sign up to request clarification or add additional context in comments.

5 Comments

This crashed the app and gave me this error Could not cast value of type '__NSArrayM' to 'NSDictionary' do you know how to solve it?
Yeah, I think I accidentally made it a dictionary. I updated my answer, but I'd definitely also recommend searching for these error messages (as that's pretty much what I'm doing).
This worked! Thank you. And I do look up these error messages but sometimes don't understand them. For example, your solution gives me the people[0] result. But when I try to get people[0]["name"] it tells me Cannot subscript a value of type '[Any]' with an index of type 'String'
So I try to turn [Any] into [Any : String] but I get Type 'Any' does not conform to protocol 'Hashable'... This is how I get stuck...
people[0] is a dictionary, where each key is string and the value is any type (since it can be both a string and a number). So people[0] as [String: Any] is the correct conversion there.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.