There is also a version of the stride
function that includes the upper bound: stride(from:through:by:)
. It looks like this does what you want:
let range = up ? stride(from: 0, through: max, by: 1) : stride(from: max, through: 0, by: -1)
Test code:
func useStrideThrough(_ max: UInt, _ up: Bool, _ stop: UInt) {
let range = up ? stride(from: 0, through: max, by: 1) : stride(from: max, through: 0, by: -1)
var result = ""
for index in range {
result += "\(index)"
if index == stop { break }
}
print("\(#function)(\(max), \(up), \(stop)) = \(result)")
}
useStrideThrough(5, true , 6) // 012345
useStrideThrough(5, false, 6) // 543210
useStrideThrough(5, true , 3) // 0123
useStrideThrough(5, false, 3) // 543