Aezharhu
Aezharhu

Reputation: 9

How to specify a range to avoid in Swift

I'm trying to make it so when I provide a value that isn't in the thirties it prints out a certain message. Here is my code:

let age = 25

if case 18...25 = age {
  print("Cool demographic")
}
else if case !(30...39) = age {
  print("not in there thirties")
}

Upvotes: 1

Views: 86

Answers (4)

Leo Dabus
Leo Dabus

Reputation: 236370

You can use pattern match operator ~=

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

You can use this pattern matching operator (~=) to test whether a value is included in a range. The following example uses the ~= operator to test whether an integer is included in a range of numbers.

let age = 29

if 18...25 ~= age {
    print("Cool demographic")
} else if !(30...39 ~= age) {
    print("not in there thirties") // "not in there thirties\n"
}

Upvotes: 3

Alex Shoshiashvili
Alex Shoshiashvili

Reputation: 489

You can also use switch, in my opinion it's a little bit more expressive than if-else:

let age = 25

switch age {
case 18...25:
    print("Cool demographic")
case _ where !(30...39 ~= age):
    print("not in there thirties")
default:
    break
}

You can find good examples with switch from Imanou Petit by this link:

Upvotes: 0

matt
matt

Reputation: 535284

I like contains rather than the unnecessarily obscure if case. There are situations where if case is needed, but this is not one of them. It's good to say what you mean. So:

let age = 25

if (18...25).contains(age) {
    print("Cool demographic")
}
else if !(30...39).contains(age) {
    print("not in their thirties")
}

Upvotes: 2

Gniem
Gniem

Reputation: 111

If age is an integer, you can do a direct comparison:

if age < 30 || age > 39 {
    print("not in thirties")
}

Upvotes: 0

Related Questions