Swift:什么是分割[String]的正确方法,导致[[String]]具有给定的子阵列大小? [英] Swift: what is the right way to split up a [String] resulting in a [[String]] with a given subarray size?

查看:116
本文介绍了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).

具体示例:


分割[1,2,3,4,5,6,7],最大分割尺寸为2

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.

推荐答案

我不会称之为漂亮,但这是一个使用<$ c的方法$ c> 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:).

一种更实用的方法就是递归数组,如下所示: / p>

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天全站免登陆