【问题标题】:How do I extract each element in __NSArrayM?如何提取 __NSArrayM 中的每个元素?
【发布时间】:2018-01-16 02:49:44
【问题描述】:

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

我想以字符串的形式获取每种成分,以使用它们的名称创建成分类的对象。这是我正在使用的方法:

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>( 香蕉, 麦片 ) ,“级别”:容易] LazyMapCollection, Any>(_base: ["ingredients": <__nsarraym>( 香蕉, 麦片 ) , "级别": 容易], _transform: (函数)) 价值: ( 香蕉, 麦片 ) __NSArrayM 价值:容易 NSTaggedPointerString

根据我阅读 Apple 关于字典的文档的理解: 我的字典的类型为 [String: Any],在这种情况下,“成分”是充当键的字符串,值可以是任何对象。我正在使用的数组是一个可变数组。

对于如何获取该数组及其各自的元素,我感到非常困惑。我尝试从 LazyMapCollection 转换为 String ,但这会将整个数组生成为字符串。我还尝试通过键“成分”访问该值,但这不能作为“无法使用String 类型的索引下标LazyMapCollection&lt;[String : Any], Any&gt; 类型的值

【问题讨论】:

    标签: arrays swift firebase google-cloud-firestore


    【解决方案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")
            }
        }
    

    【讨论】:

    • 感谢您的回答。我现在才有机会测试它。我现在可以打印出每个成分对象的名称,这意味着您的解决方案有效。
    • 如果我想启动同时获取多个属性的对象。你的这部分代码可以:if let ingredients = data["ingredients"] as 吗? [String] { // 对数组做任何你需要的事情 } 扩展成这个?如果让成分=数据[“成分”]作为? [String], let ease = data["easy"] as? String { // 处理 }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    相关资源
    最近更新 更多