如何提取__NSArrayM中的每个元素?

时间:2018-01-16 02:49:45

标签: arrays swift firebase google-cloud-firestore

我正在使用Firestore(仍处于测试阶段),我的数据结构如下:

enter image description here

我想获取每种成分作为字符串,以创建具有名称的成分类对象。这是我正在使用的方法:

private func loadIngredients(){
    let db = Firestore.firestore()
    let recipeCollectionRef = db.collection("dishes").document((recipe?.name)!)
    recipeCollectionRef.getDocument { (document, error) in
        if let document = document {
            print("Document data: \(document.data())")
            print("\(document.data().values)")
            for value in document.data().values {
                print("Value: \(value)")
                print(type(of: value))
            }
        } else {
            print("Document does not exist")
        }
    }
}

目前收益:

  

文件数据:["成分":< __ NSArrayM 0x60000025f2f0>(       香蕉,       麦片       )       ,"等级":简单]       LazyMapCollection,Any>(_ base:[" ingredients":       < __ NSArrayM 0x60000065ad60>(       香蕉,       麦片       )       ," level":easy],_ transnsform :( Function))       价值:(           香蕉,           麦片       )       __NSArrayM       价值:简单       NSTaggedPointerString

据我所知,基于阅读Apple关于词典的文档: 我的字典有[String:Any]类型,在这种情况下"成分"是作为键的字符串,值可以是任何对象。我正在使用的数组是一个Mutable Array。

我很困惑如何获得该数组及其各自的元素。我已经尝试从LazyMapCollection转换为String但是将整个数组作为字符串生成。我也试过按键&#34;成分&#34;但这不起作用&#34;不能下标LazyMapCollection<[String : Any], Any>类型的索引类型String

1 个答案:

答案 0 :(得分:1)

如您所述,document.data()是字典([String:Any])。

首先从那开始:

if let document = document, let data = document.data() as? [String:Any] {
}

现在,如果您想访问配料阵列,请执行以下操作:

if let ingredients = data["ingredients"] as? [String] {
}

你们一起得到:

private func loadIngredients(){
    let db = Firestore.firestore()
    let recipeCollectionRef = db.collection("dishes").document((recipe?.name)!)
    recipeCollectionRef.getDocument { (document, error) in
        if let document = document, let data = document.data() as? [String:Any] {
            // Get the ingredients array
            if let ingredients = data["ingredients"] as? [String] {
                // do whatever you need with the array
            }

            // Get the "easy" value
            if let east = data["easy"] as? String {
            }
        } else {
            print("Document or its data does not exist")
        }
    }