Swift : what is the right way to split up a [String] resulting in a [[String]] with a given example?

夙愿已清 提交于 2021-02-05 09:23:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!