Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

Reverse Range in Swift

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

For example:

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

is an infinite loop.

In newer versions of Swift that code compiles, but at runtime gives the error:

Fatal error: Can't form Range with upperBound < lowerBound

I know I can use 1..5 instead, calculate j = 6 - i and use j as my index. I was just wondering if there was anything more legible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update For latest Swift 3 (still works in Swift 4)

You can use the reversed() method on a range

for i in (1...5).reversed() { print(i) } // 5 4 3 2 1

Or stride(from:through:by:) method

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

stide(from:to:by:) is similar but excludes the last value

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

Update For latest Swift 2

First of all, protocol extensions change how reverse is used:

for i in (1...5).reverse() { print(i) } // 5 4 3 2 1

Stride has been reworked in Xcode 7 Beta 6. The new usage is:

for i in 0.stride(to: -8, by: -2) { print(i) } // 0 -2 -4 -6
for i in 0.stride(through: -8, by: -2) { print(i) } // 0 -2 -4 -6 -8

It also works for Doubles:

for i in 0.5.stride(to:-0.1, by: -0.1) { print(i) }

Be wary of floating point compares here for the bounds.

Earlier edit for Swift 1.2: As of Xcode 6 Beta 4, by and ReverseRange don't exist anymore :[

If you are just looking to reverse a range, the reverse function is all you need:

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

As posted by 0x7fffffff there is a new stride construct which can be used to iterate and increment by arbitrary integers. Apple also stated that floating point support is coming.

Sourced from his answer:

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...