将阵列分解为较小的阵列

时间:2016-02-28 21:33:52

标签: swift

我有一个文本字段为类别的数组 ["id", "cat", "item_name"]

["1", "cat1", "Something"]
["2", "cat2", "Something"]
["3", "cat1", "Something"]
["4", "cat1", "Something"]
["6", "cat1", "Something"]
["7", "cat2", "Something"]
["8", "cat2", "Something"]
["9", "cat2", "Something"]

为了能够在UITableView部分中使用该类别,我需要将数组拆分为更小的数组 - 对。

所以我需要:

dic["cat1"][array of items with cat1 in field]()
dic["cat2"][array of items with cat2 in field]()

你会怎么做呢?

1 个答案:

答案 0 :(得分:2)

我不会使用reducemap。相反,我会做这样的事情

var dict: [String: [[String]]] = [:]
arr.forEach() {
    if dict[$0[1]] == nil {
        dict[$0[1]] = []
    }

    dict[$0[1]]?.append($0)
}

但是,我建议您更改代码结构和模型以使用结构。因此,不要使用嵌套数组,而是执行以下操作

struct Item {
    let id: String
    let category: String
    let name: String
} 

然后代码变得更清晰,更易于阅读

let arr2 = [
    Item(id: "1", category: "cat1", name: "Something"),
    Item(id: "2", category: "cat2", name: "Something"),
    Item(id: "3", category: "cat1", name: "Something")
]
var dict2: [String: [Item]] = [:]
arr2.forEach() {
    if dict2[$0.category] == nil {
        dict2[$0.category] = []
    }

    dict2[$0.category]?.append($0)
}