jimijon
jimijon

Reputation: 2156

Loop through object fields in firestore with Swift

I have a document. It has a bunch of object fields in "products" How do I loop through this dictionary?

let dict = doc.data()

for (key,value) in dict["products"]{

}

This gives me the error:

Type 'Any?' does not conform to protocol 'Sequence'

What is my obvious problem?

EDIT: The docs say

/**
* Retrieves all fields in the document as an `NSDictionary`.
*
* @return An `NSDictionary` containing all fields in the document.
*/
- (NSDictionary<NSString *, id> *)data;

Upvotes: 0

Views: 644

Answers (1)

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

You should use:

let dict = doc.data()

if let products = dict["products"] as? [AnyHashable: Any] {

    for (key,value) in products {

    }
}

doc.data() returns Any?, so in order to treat it as a Dictionary you need to cast it to Dictionary.

Upvotes: 1

Related Questions