我在 Swift 中有一个嵌套数组,其中每个内部数组的大小可能不同:
let numbers = [[0], [1], [2, 3], [4]]
问题是我需要根据单个索引值修改一个条目(基本上基于展平数组的索引;所以在这个例子中,每个值基本上都是它的索引)。
通过 flatMap
调用我已经解决了一半的问题,但我不确定之后如何重新嵌套它,或者我是否一开始就采取了错误的方法.
func setValue(_ value: Int, index: Int, list: [[Int]]) -> [[Int]]
{
var output = numbers.flatMap { $0 }
output[index] = value
// TODO: Re-nest
return [output]
}
let output = setValue(42, index: 3, list: numbers)
print(output) // [[0, 1, 2, 42, 4]]
我如何制作此输出 [[0], [1], [2, 42], [4]]
,是否有更优雅(功能)的方式来实现此目的?
最佳答案
我有一个使用两张 map 的(有点)功能性解决方案。
func setValue(_ value: Int, index: Int, list: [[Int]]) -> [[Int]] {
var i = -1
return list.map { arr in
return arr.map { e in
i += 1
if (i == index) { return value }
else { return e }
}
}
}
我没有太多时间思考解决这个问题的巧妙方法,但这是我的 hacky 方法。
关于arrays - 在 Swift 中修改嵌套数组条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45945460/