How to map an array in a Firestore document to Swift?

struct maindata {

    var userID: String

    var extended: [Contents]

    init(Doc: DocumentSnapshot) {

        self.userID = Doc.get(“userID”) as? String ?? “nil”

        extended = []

        let data = Doc.data( )

        if let testarr = data?[“testarr”] as? [[String: Any]]{

            testarr.forEach { sany in

                if let content = Contents(data: sany){

                    self.extended.append(content)

                }

            }

        }

    }

}

struct Contents {

    var IDone: String

    var IDtwo: String

    init?(data: [String: Any]) {

        self.IDone = data[“one”] as? String ?? “”

        self.IDtwo = data[“two”] as? String ?? “”

    }

}

How to use example

Firestore.firestore().collection(“LiveApi”).document(“test”).getDocument { docsnap, error in

            if let docs = docsnap {

                let data = maindata(Doc: docs)

                data.extended.first?.IDone

                data.extended[1].IDtwo

            }

        }

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.