gpt4 book ai didi

swift - 将数组分解/拆分为更小的数组

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:39 24 4
gpt4 key购买 nike

我有一个数组,其中一个文本字段是一个类别
["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]()

你会怎么做?

最佳答案

我不会为此使用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)
}

关于swift - 将数组分解/拆分为更小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35688561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com