Reverse Range in Swift

前端 未结 7 1289
青春惊慌失措
青春惊慌失措 2020-11-27 14:07

Is there a way to work with reverse ranges in Swift?

For example:

for i in 5...1 {
  // do something
}

is an infinite loop.

7条回答
  •  一生所求
    2020-11-27 14:57

    It appears that the answers to this question have changed a bit as we've progressed through the betas. As of beta 4, both the by() function and the ReversedRange type have been removed from the language. If you're looking to make a reversed range, your options are now as follows:

    1: Create a forward range, and then use the reverse() function to reverse it.

    for x in reverse(0 ... 4) {
        println(x) // 4, 3, 2, 1, 0
    }
    
    for x in reverse(0 ..< 4) {
        println(x) // 3, 2, 1, 0
    }
    

    2: Use the new stride() functions that were added in beta 4, which includes functions to specify the starting and ending indexes, as well as the amount to iterate by.

    for x in stride(from: 0, through: -8, by: -2) {
        println(x) // 0, -2, -4, -6, -8
    }
    
    for x in stride(from: 6, to: -2, by: -4) {
        println(x) // 6, 2
    }
    

    Note that I've also included the new exclusive range operator in this post as well. .. was replaced with ..<.

    Edit: From the Xcode 6 beta 5 release notes, Apple added the following suggestion for handling this:

    ReverseRange has been removed; use lazy(x..

    Here's an example.

    for i in lazy(0...5).reverse() {
        // 0, 1, 2, 3, 4, 5
    }
    

提交回复
热议问题