UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: A newbie question about conditions >, < or ..<, ...

Forums > Swift

@Allen  

dunno what's the difference or the point of ..< and ... when <, >, <= or >= are already there to be the range operator.. re them the similiar ?

2      

>, <, >=, and <= aren't range operators, though; they are comparison operators. So to use them to test for inclusion in a range requires multiple comparisons in combination with logical operators.

Which of these examples looks and reads better?

//using the ~= operator
if 0..<10 ~= i {
    print("\(i)")
}

//using the Range.contains() method
if (0..<10).contains(i) {
    print("\(i)")
}

if i >= 0 && i < 10 {
    print("\(i)")
}

Its also far, far easier to loop through a range with something like this:

for i in 0...10 {
    print("\(i)")
}

than this:

i = 0
while i >= 0 && i <= 10 {
    print("\(i)")
    i += 1
}

Especially because when using comparison operators like in that last example, it is very easy to mess up and use, say, < 10 when you mean to say <= 10.

4      

@Allen  

Thanks a lot such a high quality reply dude. I get it so they re not used mostly in range but to compare both values, it is bit more convenient and simple to use ... with less combination operator as well.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.