问题
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).
Concrete example: Split up ["1","2","3","4","5","6","7","8","9"] with max split size 4
The code would produce [["1","2","3","4"],["4","5","6","7"],["7","8","9"]]
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.
回答1:
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"]]
来源:https://stackoverflow.com/questions/61696952/swift-what-is-the-right-way-to-split-up-a-string-resulting-in-a-string-w