7

I was wondering if there is any smooth way of checking the value of an integer in a range in swift.

I have an integer that can be any number between 0 and 1000

I want to write an if statement for "if the integer is between 300 and 700 - do this and if its any other number - do something else"

I could write:

if integer > 300 {
    if integer < 700 {
      //do something else1
    }
    //do something
} else {
    // do something else2

}

But I want to minimize the amount of code to write since "do something else1" and "do something else2" are supposed to be the same

It doesn't seem that you can write :

if 300 < integer < 700 {

} else {

}

I tried using

if integer == 300..<700 {
}

but that didn't work either. Anybody got a suggestion?

3

2 Answers 2

13

Did you try this?

if integer > 300 && integer < 700 {
    // do something
} else {
    // do something else               
}

Hope this helps

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that does work! I thought there might have been an even shorter way of writing it without repeating with && and "integer" but this might be the best way. Thank you
Actually I did find a shorter way that Martin R pointed to You can write: if 300 ... 700 ~= integer { }
William +1 but use the half open operator!
10

There is a type, HalfOpenInterval, that can be constructed with ... and that has a .contains method:

if (301..<700).contains(integer) {
    // etc.
}

Note, 301..<700 on its own will create a Range, which doesn’t have a contains function, but Swift’s type inference will see that you’re calling a method that only HalfOpenInterval has, and so picks that particular overload.

I mention this just because if you want to store the interval as a variable instead of using it in-line, you need to specify:

let interval = 301..<700 as HalfOpenInterval
if interval.contains(integer) {
  // etc.
}

4 Comments

Interestingly, with Xcode 6.3 in optimized mode, this also gives the same "optimal" assembly code as if integer > 300 && integer < 700 or if 300 ... 700 ~= integer which I just added to stackoverflow.com/a/24893494/1187415.
Yeah apparently all the standard library code can be inlined (and the swift compiler is very keen to inline with -O)
And as Willian Larson points out, the contains operator can be used for shorter syntax, in if 300..<700 ~= integer {
I’m not sure that’s really the intended use of the ~= operator, I see that more as the underlying mechanism for switch rather than something supposed to be used stand-alone. .contains signals intent more clearly IMHO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.