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)'
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:
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With