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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With