【问题标题】:How to append to [[String : [String]]] = [[:]] instead of [String : [String]] = [:]?如何附加到 [[String : [String]]] = [[:]] 而不是 [String : [String]] = [:]?
【发布时间】:2020-07-22 18:12:10
【问题描述】:

我正在从 Firestore 数据库中获取数组列表并将其附加到以下变量:

var productTags : [String : [String]] = [:]

这是我获取数据并将其附加到productTags 变量的代码:

db.collection(DatabaseRef.searchTags).document(DatabaseRef.productTags).getDocument { snapshot, error in

            guard error == nil, let snapshot = snapshot else {
                return
            }

            let data = snapshot.data()!


            for (key, _) in data {

                let productTags = data["\(key)"] as? [Any]

                if let maxIndex = productTags?.count {

                    for index in 0..<maxIndex {

                        if let tag = productTags![index] as? String, tag != "" {

                            if self.productTags[key] == nil {
                                self.productTags[key] = []
                                self.productTags[key]?.append(tag)
                            } else {
                                self.productTags[key]?.append(tag)
                            }

                        }
                    }

                }
            }
        }

这工作得很好,并给了我以下结果:

productTags = [ product1 : [tag1, tag2, tag3, tag4],
                product2 : [tag1, tag2, tag3, tag4, tag 5], 
                product3 : [tag1, tag2, tag3]
              ] 

但是,我需要把字典变成一个数组,这样结果就会像这样:

productTags = [ [product1 : [tag1, tag2, tag3, tag4]],
                [product2 : [tag1, tag2, tag3, tag4, tag 5]], 
                [product3 : [tag1, tag2, tag3]]
              ] 

所以我的变量应该是这样的:

var productTagsArray : [[String : [String]]] = [[:]]

如何更改我的代码,以便将其附加到数组而不是字典中?

【问题讨论】:

    标签: arrays swift dictionary arraylist append


    【解决方案1】:

    我建议在完成后将字典转换为数组:

    let productTagsArray = productTags.map { [$0: $1] }
    

    另外,您可以使用default 版本的字典查找来更改:

    if self.productTags[key] == nil {
        self.productTags[key] = []
        self.productTags[key]?.append(tag)
    } else {
        self.productTags[key]?.append(tag)
    }
    

    进入这个:

    self.productTags[key, default: []].append(tag)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 2013-08-30
      • 2012-09-12
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多