How to check if an Int in a constant, matches an Int in a CountableClosedRange<Int>

Viewed 101

I'm new to programming. Self teaching so I wanted to ask the internet for help.

I wanted to see if an Int I stored in a constant, matches a single digit in a CountableClosedRange, and if so, spit out the boolean value true. See below:

let physics = 76
let math = 79
let history = 94
let language = 98


let aPlus = [95...100]

let didPhysicsGetA = physics == aPlus

76 is obviously not in that range, so in this case I'd want didPhysicsGetA to comeback as false.

How can I do so, and are there better ways?

3 Answers

[] denotes an array. You just want a range, not an array of ranges, so you should remove the []:

let aPlus = 95...100

To check if a number is in a range, you can either use the ~= pattern matching operator,

aPlus ~= physics

or call contains:

aPlus.contains(physics)

You should choose whichever is the most readable to you.

First of all [95...100] will result in [CountableClosedRange<Int>] means array of CountableClosedRange<Int>. So what you need is (95...100).

let aPlus = (95...100) // or you can even emit the brackets 95...100

Now to check Int is in this aPlus range you can use pattern match operator ~= like this.

let didPhysicsGetA = aPlus ~= physics
print(didPhysicsGetA) // false

Try this :

let physics = 76
let language = 98

let aPlus = 95...100

print(aPlus ~= physics) // false
print(aPlus ~= language) // true

OR

aPlus.contains(physics) // false
aPlus.contains(language) // true
Related