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

前端 未结 1 1193
囚心锁ツ
囚心锁ツ 2021-01-28 09:11

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

1条回答
  •  粉色の甜心
    2021-01-28 10:03

    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.. [["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"]]
    
    

    0 讨论(0)
提交回复
热议问题