当我在Playground中使用for循环时,一切都很好,直到我将for循环的第一个参数更改为最大值。(按降序迭代)

这是一个bug吗?还有其他人有吗?

for index in 510..509
{
    var a = 10
}

显示将要执行的迭代次数的计数器一直在滴答作响……


当前回答

斯威夫特4.0

for i in stride(from: 5, to: 0, by: -1) {
    print(i) // 5,4,3,2,1
}

如果你想包含to值:

for i in stride(from: 5, through: 0, by: -1) {
    print(i) // 5,4,3,2,1,0
}

其他回答

反转一个数组只需要一个步骤。reverse()

var arrOfnum = [1,2,3,4,5,6]
arrOfnum.reverse()

对于Swift 2.0及以上版本,你应该在range collection上应用reverse

for i in (0 ..< 10).reverse() {
  // process
}

在Swift 3.0中已被重命名为.reversed()

在Swift 4及后续版本中

    let count = 50//For example
    for i in (1...count).reversed() {
        print(i)
    }

这将以相反的顺序递减1。

let num1 = [1,2,3,4,5]
for item in nums1.enumerated().reversed() { 

    print(item.offset) // Print the index number: 4,3,2,1,0
    print(item.element) // Print the value :5,4,3,2,1

}

或者你可以用这个index value属性

let num1 = [1,2,3,4,5]
for (index,item) in nums1.enumerated().reversed() { 

    print(index) // Print the index number: 4,3,2,1,0
    print(item) // Print the value :5,4,3,2,1

}

Swift向前

for i in stride(from: 5, to: 0, by: -1) {
    print(i)
}
//prints 5, 4, 3, 2, 1

for i in stride(from: 5, through: 0, by: -1) {
    print(i)
}
//prints 5, 4, 3, 2, 1, 0