gpt4 book ai didi

arrays - 如何使用函数式编程将字典转换为 IndexPath 数组?

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

我有这种字典。

let sections = ["A": ["Item1", "Item2", "Item3", "Item4"], "B": ["Item1", "Item2", "Item3", "Item4"]]

我需要在创建 IndexPath 数组之前获取所有键并对它们进行排序。

let sectionsKeys = Array(sections.keys).sorted()

现在我需要将这个字典转换为 IndexPath 数组。

var indexPathes = [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3]]

所以我的尝试非常简单。

for (sectionPos,key) in sectionsKeys.enumerated() {
guard let items = sections[key] as? [String] else {
break
}
for (itemPos,_) in items.enumerated() {
let indexPath = IndexPath(row: itemPos, section: sectionPos)
indexPathes.append(indexPath)
}

这样我收到了预期的结果。

但我正在寻找将使用函数式编程来实现相同结果的解决方案。

最佳答案

首先,您应该对 sections 字典进行排序(生成元组数组),因为字典根据定义是无序的,因此无法保证通过迭代字典本身您会得到想要的结果。

之后您可以枚举有序集合,然后使用 flatMapmap 的组合来创建 IndexPath。在遍历各个部分以展平嵌套 map 返回的 IndexPath 数组时,您需要 flatMap

您可以使用 section.value.indices 遍历索引本身,而不是遍历枚举集合以仅获取索引,其中 value 是类型[字符串]

let sections = ["Section 1": ["Item1", "Item2", "Item3", "Item4"], "Section 2": ["Item1", "Item2", "Item3", "Item4"]]

let indexPaths = sections.sorted(by: {$0.key < $1.key}).enumerated().flatMap({sectionPos, section->[IndexPath] in
return section.value.indices.map({ itemPos->IndexPath in
IndexPath(row: itemPos, section: sectionPos)
})
})

输出:

[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3]]

关于arrays - 如何使用函数式编程将字典转换为 IndexPath 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48165848/

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