In Swift, the c-style for-loop is deprecated, so I am switching to the stride function.
In the first function, I use a c-style for-loop. In the second function, I used the stride function. createNumbers output is [8, 7, 6, 5, 4, 3, 2] createNumbers2 output is [8, 7, 6, 5, 4] I am trying to get the first output.
That means the stride function will ignore if I change the endIdx value. Is there a way to work around this, using stride, such that createNumbers2 also prints 3 and 2?
func createNumbers(lastNum: Int) -> [Int] {
var endIdx = lastNum
var answer : [Int] = []
for var i = 8; i >= endIdx; i -= 1 {
answer.append(i)
if i == 6 {
endIdx /= 2
}
}
return answer
}
func createNumbers2(lastNum: Int) -> [Int] {
var endIdx = lastNum
var answer : [Int] = []
for i in 8.stride(through: endIdx, by: -1) {
answer.append(i)
if i == 6 {
endIdx /= 2
}
}
return answer
}
print(createNumbers(4)) // [8, 7, 6, 5, 4, 3, 2]
print(createNumbers2(4)) // [8, 7, 6, 5, 4]