Determine if a Range contains a value

Posted by Brad Dwyer on Stack Overflow See other posts from Stack Overflow or by Brad Dwyer
Published on 2014-06-03T20:53:08Z Indexed on 2014/06/03 21:25 UTC
Read the original article Hit count: 188

Filed under:

I'm trying to figure out a way to determine if a value falls within a Range in Swift.

Basically what I'm trying to do is adapt one of the examples switch statement examples to do something like this:

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

As far as I can tell, there isn't any built in way to do what my imaginary .contains method above does.

So I tried to extend the Range class. I ended up running into issues with generics though. I can't extend Range<Int> so I had to try to extend Range itself.

The closest I got was this but it doesn't work since >= and <= aren't defined for ForwardIndex

extension Range {
    func contains(val:ForwardIndex) -> Bool {
        return val >= self.startIndex && val <= self.endIndex
    }
}

How would I go about adding a .contains method to Range? Or is there a better way to determine whether a value falls within a range?

Edit2: This seems to work to extend Range

extension Range {
    func contains(val:T) -> Bool {
        for x in self {
            if(x == val) {
                return true
            }
        }

        return false
    }
}

var a = 0..5
a.contains(3) // true
a.contains(6) // false
a.contains(-5) // false

I am very interested in the ~= operator mentioned below though; looking into that now.

© Stack Overflow or respective owner

Related posts about swift-language