Swift:拆分 [String] 得到具有给定子数组大小的 [[String]] 的正确方法是什么? [英] Swift: what is the right way to split up a [String] resulting in a [[String]] with a given subarray size?

查看:37
本文介绍了Swift:拆分 [String] 得到具有给定子数组大小的 [[String]] 的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从一个大的 [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).

具体例子:

使用最大拆分大小 2 拆分 [1"、2"、3"、4"、5"、6"、7"]

Split up ["1","2","3","4","5","6","7"] with max split size 2

代码将产生 [[1"、2"]、[3"、4"]、[5"、6"]、[7"]]

The code would produce [["1","2"],["3","4"],["5","6"],["7"]]

显然我可以更手动地执行此操作,但我觉得像 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 的方法:

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)
    }
}

这篇关于Swift:拆分 [String] 得到具有给定子数组大小的 [[String]] 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆