Swift - 具有恒定字符串数的多个子数组的字符串数组

时间:2015-05-13 17:08:50

标签: arrays swift

假设我有这个字符串数组:

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

我想要的是这个结果:

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

我知道我可以通过for执行此操作,但我想在Swift中使用高阶函数。我的意思是map,reduce,filter等功能。我认为这样做可能会更好。谁能帮我这个?感谢

1 个答案:

答案 0 :(得分:5)

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]]

闭包中advance()的使用保证了代码 即使数组元素的数量不是4的倍数也能工作 (然后结果中的最后一个子阵列会更短。)

您可以将其简化为

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

如果您知道数组元素的数量是4的倍数。

严格地说resultArray的元素不是数组 但是数组切片。在许多情况下无关紧要,否则你

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