Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare ranges in Swift?

Tags:

swift

I'm not sure if it's a bug in XCode or I didn't understand ranges in Swift. Here is some code to show how range works:

let range = 0..<5
contains(range, 0) // true
contains(range, 5) // false
range.startIndex == 0 // true
range.endIndex == 5 // true

let str = "Hello, playground"
str.rangeOfString("Hello")! // 0..<5

Great! Now let's use it real code:

let str = "Hello, playground"
if let range = str.rangeOfString("Hello") {
    if range.startIndex == 0 {
        print("str starts with 'Hello'")
    }
}

I'm getting following error in line that reads if range.startIndex == 0 {

Cannot invoke '==' with an argument lis of type (String.index, IntegerLiteralConvertible)'

like image 663
Mohsen Avatar asked Oct 29 '14 23:10

Mohsen


1 Answers

The ~= operator in Swift

Sometimes, we have to check if a number is between a range, and as usual, we do something like :

Check if number is between 0 and 100 include

if number >=0 && number <= 100 {  
   // TODO:
}

It works, but we can do better and swiftier. The Swift Standard library have an ~= operator, so we can do instead :

if 0...100 ~= number {  
   // TODO:
 }
like image 89
Premkumar Avatar answered Sep 27 '22 16:09

Premkumar