Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if integer is greater than x but less than y (Swift)

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?

like image 357
William Larson Avatar asked Apr 04 '15 13:04

William Larson


People also ask

What does the=== operator do in Swift?

The === or identity operator compares the identity of the objects. It checks whether the operands refer to the same object. As you can see, arr1 and arr2 do not refer to the same object, despite the objects being equal.

What does != Mean in Swift?

Types that conform to the Equatable protocol can be compared for equality using the equal-to operator ( == ) or inequality using the not-equal-to operator ( != ). Most basic types in the Swift standard library conform to Equatable .

Is ++ valid in Swift?

Swift provides an increment operator ++ and a decrement operator to increase or decrease the value of a numeric variable by 1. The operator with variables of any integer or floating-point type is used. The ++ and -- symbol is used as a prefix operator or postfix operator.


2 Answers

Did you try this?

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

Hope this helps

like image 174
CrApHeR Avatar answered Oct 26 '22 17:10

CrApHeR


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.
}
like image 44
Airspeed Velocity Avatar answered Oct 26 '22 16:10

Airspeed Velocity