Create a if statement with a range of ints

I want to make a if statement that equals several different numbers. A example is below that compels but writing score every time could take a lot of time.

if score == 4 || score  == 5 || score == 6 {

print("Yes")

I want to somehow write a if statement that goes like

if score == {4,5,6}{
print ("yes")}

The simplest way I can think of would be to use contains which comes from the Sequence protocol

if [4, 5, 6].contains(score) {
    print("Yes")
}
1 Like

that works thanks i test it.

With the provided values/sample, I would have used contains(:)->Bool from the RangeExpression protocol

if Range(4...6).contains(score) { print("Yes") }

@mokhet’s solution is best if your ints represent a range. You can shorten it to:

if 4...6 ~= score { print("Yes") }

1 Like

@timswift You can also use if case with ranges like this:

if case 4...6 = score {
  print("yes")
}

I hope it helps!

1 Like