字典中的数组数组

时间:2016-12-27 00:08:57

标签: swift dictionary

我有一个字典初始化:

var itemsSections = Dictionary<String, [Item?]>()

字典的键应该是购物项目的类型(&#34;动物,婴儿,饮料,美容......),值可以是项目数组。

我的项目类似于:

Class Item :
    public var created: NSCreatedDate?
    public var details: String?
    public var title: String?
    public var unity: float?
    public var quantity: int?
    public var type : String?

当我初始化字典时,我不知道将填充多少种类型,以及每个数组中可以有多少项。

当我添加该对时,我收到错误:

//populate the sections

for (item) in self.items
{
    let typeName = (item.type)!

    //itemsSections[typeName]?.append(item) -> this compiles, but the dictionary remain with nothing 

    //itemsSections[typeName]!.append(item) this won't compile,

    //itemsSections[typeName] = [item] -> this works, but if i have one type that is in more than one item, it only shows 1.
}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

这个怎么样?

for (item) in self.items
{
    let typeName = (item.type)!

    var value = itemSections[typeName] ?? []
    value.append(item)
    itemSections[typeName] = value
}

Array是struct。 itemSections[typeName]检索到的值将被复制一个,而不是itemSections中的实际数据。您无法直接将项添加到itemSections的数据中。您必须将其附加到复制的数组并再次使用它更新itemSections

此外,当nil没有itemSections的数据时,检索到的值为typeName。在这种情况下,需要初始的空数组。这就是?? []

的原因
相关问题