假设我有这个字符串数组:
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等功能。我认为这样做可能会更好。谁能帮我这个?感谢
答案 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)])
}