JoGoFo
JoGoFo

Reputation: 2008

Swift Range Operator with two unknown values

If I have two unknown values, lets say x and y, what is the best way loop through all of the values between between those values?

For example, given the values x = 0 and y = 5 I would like to do something with the values 0, 1, 2, 3, 4, and 5. The result could exclude 0 and 5 if this is simpler.

Using Swift's Range operator, I could do something like this:

for i in x...y {
    // Do something with i
}

Except I do not know if x or y is the greater value.

The Swift documentation for Range Operators states:

The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.

There are a number of solutions here. A pretty straight forward one is:

let diff = y - x

for i in 0...abs(diff) {
    let value = min(x, y) + i
    // Do something with value
}

Is there a better, or more elegant way to achieve this?

Upvotes: 0

Views: 137

Answers (1)

Jean-Baptiste
Jean-Baptiste

Reputation: 967

I guess the most explicit way of writing it would be:

for i in min(a, b)...max(a, b) {
    // Do something with i
}

To exclude the first and last value, you can increment your lower limit and use the Swift ..< syntax:

let lowerLimit = min(a, b) + 1
let upperLimit = max(a, b)

for i in lowerLimit..<upperLimit {
    // Do something with i
}

Upvotes: 2

Related Questions