Swift:使用给定示例拆分[String]导致[[String]]的正确方法是什么? [英] Swift : what is the right way to split up a [String] resulting in a [[String]] with a given example?
问题描述
从较大的[String]和给定的子数组大小开始,将这个数组拆分为较小的数组的最佳方法是什么?(最后一个数组将小于给定的子数组大小.)
Starting with a large [String] and a given subarray size, what is the best way I could go about splitting up this array into smaller arrays? (The last array will be smaller than the given subarray size).
具体示例:拆分[[1," 2," 3," 4," 5," 6," 7," 8," 9],最大拆分大小为4
Concrete example: Split up ["1","2","3","4","5","6","7","8","9"] with max split size 4
代码将产生[["1","2","3","4"],["4","5","6","7"],["7","8," 9]]
The code would produce [["1","2","3","4"],["4","5","6","7"],["7","8","9"]]
很显然,我可以手动进行一些操作,但是我觉得像map()或reduce()这样的东西可能会做得很漂亮.
Obviously I could do this a little more manually, but I feel like in swift something like map() or reduce() may do what I want really beautifully.
推荐答案
您可以对索引进行 map
到数组中:
You can map
over the indices into you array:
extension Array {
func chunked(size: Int) -> [[Element]] {
let cnt = self.count
return stride(from: 0, to: cnt, by: size).map {
let end = Swift.min($0 + size, cnt)
return Array(self[$0..<end])
}
}
}
["1","2","3","4","5","6","7","8","9"].chunked(size: 4)
// -> [["1", "2", "3", "4"], ["5", "6", "7", "8"], ["9"]]
["1","2","3","4","5","6","7","8","9"].chunked(size: 3)
// -> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]
这篇关于Swift:使用给定示例拆分[String]导致[[String]]的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!