且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift:拆分 [String] 得到具有给定子数组大小的 [[String]] 的正确方法是什么?

更新时间:2023-11-26 21:26:46

我不会说它漂亮,但这里有一个使用 map 的方法:

I wouldn't call it beautiful, but here's a method using map:

let numbers = ["1","2","3","4","5","6","7"]
let splitSize = 2
let chunks = numbers.startIndex.stride(to: numbers.count, by: splitSize).map {
  numbers[$0 ..< $0.advancedBy(splitSize, limit: numbers.endIndex)]
}

stride(to:by:) 方法为您提供每个块的第一个元素的索引,因此您可以使用 advancedBy(距离:限制:).

The stride(to:by:) method gives you the indices for the first element of each chunk, so you can map those indices to a slice of the source array using advancedBy(distance:limit:).

一种更功能性"的方法就是对数组进行递归,如下所示:

A more "functional" approach would simply be to recurse over the array, like so:

func chunkArray<T>(s: [T], splitSize: Int) -> [[T]] {
    if countElements(s) <= splitSize {
        return [s]
    } else {
        return [Array<T>(s[0..<splitSize])] + chunkArray(Array<T>(s[splitSize..<s.count]), splitSize)
    }
}