stride函数,为可变步长类型值的序列
其中from to
,最后一个值将会小(大)于to的值
for index in stride(from:0, to:3, by:1) {
print(index)
}
// print 0, 1, 2
for index in stride(from:3, to:0, by:-1) {
print(index)
}
// print 3,2,1
而from through
,最后一个值将会小(大)于等于through的值
for index in stride(from:0, through:3, by:1) {
print(index)
}
// print 0, 1, 2, 3
for index in stride(from:3, through:0, by:-1) {
print(index)
}
// print 3,2,1,0
调整by
参数(步长)
for index in stride(from: 0, to: 9, by: 3) {
print(index)
}
// print 0, 3, 6
// through,包含末尾
for index in stride(from: 0, through: 9, by: 3) {
print(index)
}
// prints 0, 3, 6, 9
数组分割
ps:步长与数组元素个数刚好整数倍,否则多出的元素会舍去
var array = Array(1...10)
let group1Arr = stride(from: 0, to: 8, by: 4).map {
print(array[$0...$0+3])
}
//[1, 2, 3, 4]
//[5, 6, 7, 8]
let group2Arr = stride(from: 0, to: 8, by: 4).map {
Array(array[$0...$0+3])
}
print(group2Arr)
// [[1, 2, 3, 4], [5, 6, 7, 8]]
或
let step = 3
let finalArray = stride(from: 0, to: array.endIndex - (array.endIndex % step), by: step).map {
Array(array[$0...$0+(step - 1)])
}
// step = 2
// [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
// step = 3
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]