the Reverend the Reverend - 4 months ago 25
Swift Question

Swift Range Type endIndex

If you create a var Range = 0...0, I would expect the endIndex to be zero. But in reality is 1.

var myRange: Range<Int> = 0...0
print("start Index \(myRange.startIndex) End Index \(myRange.endIndex)")



output: "start Index 0 End Index 1"


How can I question a Range instance if an Index of type Int is contained ?

Answer

The endIndex is not actually included in the Range. The Range is startIndex ..< endIndex. So, for your example, 0...0 is stored as 0..<1 which means the same thing.

For Swift 1.2 you can use the global function contains to check if an Int is contained by a Range:

var myRange: Range<Int> = 0...0
let i: Int = 1

if contains(myRange, i) {
    println("yes")
} else {
    println("no")    // prints "no"
}

For Swift 2.0:

var myRange: Range<Int> = 0...0
let i: Int = 1

if myRange.contains(i) {
    print("yes")
} else {
    print("no")    // prints "no"
}