简体   繁体   English

Swift-将字符串数组转换为具有恒定字符串数的多个子数组

[英]Swift - array of strings to multiple subarrays with constant number of strings

Let's say I have this array of strings: 假设我有以下字符串数组:

let Vehicles = ["Aeroplane", "Bicycle", "CarVehicle", "Lorry", "Motorbike", "Scooter", "Ship", "Train"]

What I want is this result: 我想要的是这个结果:

let resultArray = [["Aeroplane", "Bicycle", "CarVehicle", "Lorry"], ["Motorbike", "Scooter", "Ship", "Train"]]

I know I could do this by for but I want to use Higher Order functions in Swift. 我知道我可以这样做for但是我想在Swift中使用高阶函数。 I mean functions like map, reduce, filter. 我的意思是像map,reduce,filter之类的功能。 I think it's possible to do this way and it could be better. 我认为这样做是可能的,而且可能会更好。 Can anyone help me with this? 谁能帮我这个? Thanks 谢谢

A possible solution with map() and stride() : map()stride()可能解决方案:

let vehicles = ["Aeroplane", "Bicycle", "CarVehicle", "Lorry", "Motorbike", "Scooter", "Ship", "Train"]
let each = 4

let resultArray = map(stride(from: 0, to: vehicles.count, by: each)) {
    vehicles[$0 ..< advance($0, each, vehicles.count)]
}

println(resultArray)
// [[Aeroplane, Bicycle, CarVehicle, Lorry], [Motorbike, Scooter, Ship, Train]]

The usage of advance() in the closure guarantees that the code works even if the number of array elements is not a multiple of 4 (and the last subarray in the result will then be shorter.) 即使数组元素的数量不是4的倍数,在闭包中使用advance()保证代码正常工作(结果中的最后一个子数组将更短)。

You can simplify it to 您可以简化为

let resultArray = map(stride(from: 0, to: vehicles.count, by: each)) {
    vehicles[$0 ..< $0 + each]
}

if you know that the number of array elements is a multiple of 4. 如果您知道数组元素的数量是4的倍数。

Strictly speaking the elements of resultArray are not arrays but array slices. 严格来说, resultArray的元素不是数组,而是数组切片。 In many cases that does not matter, otherwise you can replace it by 在许多情况下都没关系,否则您可以将其替换为

let resultArray = map(stride(from: 0, to: vehicles.count, by: each)) {
    Array(vehicles[$0 ..< advance($0, each, vehicles.count)])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM