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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.