如何从Firestore获取数组字段并在Swift中写入struct字段?

时间:2019-03-26 10:03:17

标签: swift firebase struct google-cloud-firestore

我面临的问题是,我可以访问Firestore中的每个字段并写入除array&map字段之外的结构。

我的Firestore数据类似于:

 let data : [String : Any] = [
                "name" : "House A",
                "price" : 2000,
                "contents" : [
                   "water" : true,
                   "internet" : false
                ]
            ]

这是getDocument函数:

let docRef = db.collection("example").document("example")

docRef.getDocument { (document, error) in
            if let document = document, document.exists {

                let data = Houses(Doc: document)
                ...
                ...
                ...
            } else {
                print(error, "Item not found")
            }
        }        

这是我的结构:

struct Houses {
    var name: String?
    var price: Int
    var contents : Contents

    init(Doc: DocumentSnapshot){

        self.name = Doc.get("name") as? String ?? ""
        self.price = Doc.get("price") as! Int
        self.contents = Doc.get("contents") as! Contents
    }
}

struct Contents  {
    var water: Bool
    var internet : Bool

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

        guard let water = data["water"] as? Bool,
            let internet = data["internet"] as? Bool else {
                return nil
        }

        self.water = water
        self.internet = internet

    }
}

其他版本的内容:

struct Contents  {
    var water: Bool
    var internet : Bool

    init(Doc: DocumentSnapshot){
        self.water = Doc.get("water") as! Bool
        self.internet = Doc.get("internet") as! Bool
    }
}

已更新 通过更改此行解决了问题:

self.contents = Doc.get("contents") as! Contents

至;

self.contents = Contents(data: Doc.get("contents") as! [String : Any])

名称价格返回了我期望的值,但是内容始终返回。我尝试配置内容,但结果相同。我认为,我必须配置名为 Contents 的结构。

任何帮助将不胜感激。

0 个答案:

没有答案