Determine if a Range contains a value

You can do it with the ~= operator:

let point = (1, -1)
switch point {
case let (x, y) where (0..5) ~= x:
   println("(\(x), \(y)) has an x val between 0 and 5.")
default:
   println("This point has an x val outside 0 and 5.")
}

You can also do it directly in a switch:

let point = (1, -1)
let (x, y) = point
switch x {
case 0..5:
    println("yes")
default:
    println("no")
}

~= is the pattern match operator used by case statements. See details in the docs.


Instead of messing with Range, you could add a simple helper function like this

let point = (1, -1)
switch point {
case let (x, y) where contains((0..5),x):
    println("(\(x), \(y)) has an x val between 0 and 5.")
default:
    println("This point has an x val outside 0 and 5.")
}

func contains(range :Range<Int>, x: Int)->Bool{
    for num in range{
        if(num==x){
            return true
        }
    }
    return false
}

You could also probably do something similar with a closure.


With Swift 5, according to your needs, you may choose one of the following options to determine if a Range (or a ClosedRange) contains a value.


1. contains(_:) method

Range, ClosedRange, CountableRange and CountableClosedRange have a contains(_:) method. Range contains(_:) method has the following declaration:

func contains(_ element: Bound) -> Bool

Returns a Boolean value indicating whether the given element is contained within the range.

Usage:

let value: Int = 0
let range = -200 ..< 300
print(range.contains(value)) // prints true

2. ~=(_:_:) operator

Range, ClosedRange, CountableRange and CountableClosedRange have a ~=(_:_:) operator. Range ~=(_:_:) operator has the following declaration:

static func ~= (pattern: Range<Bound>, value: Bound) -> Bool

Returns a Boolean value indicating whether a value is included in a range.

Usage:

let value = 0
let range = -200 ..< 300
print(range ~= value) // prints true

3. Switch statement

A simple way to test if a Range, a ClosedRange, a CountableRange or a CountableClosedRange contains a value is to use a switch statement:

let value = 0
switch value {
case -200 ..< 300:
    print("OK") // prints "OK"
default:
    break
}

4. Pattern matching with if case

As an alternative to the previous switch statement, you can use if case:

let value = 0
if case -200 ..< 300 = value {
    print("OK") // prints "OK"
}  

Therefore, in order to solve your problem, you can use one of the following options:

let point = (1, -1)
switch point {
case let (x, y) where (0 ..< 5).contains(x):
    print("(\(x), \(y)) has an x val between 0 and 5.")
default:
    print("This point has an x val outside 0 and 5.")
}
let point = (1, -1)
if case let (x, y) = point, 0 ..< 5 ~= x {
    print("(\(x), \(y)) has an x val between 0 and 5.")
}

Tags:

Range

Swift