Swift Range endIndex type

If you create var Range = 0 ... 0, I would expect endIndex to be zero. But in fact it 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 poll an instance of Range if an Int is specified?

+3


source to share


3 answers


endIndex

not actually included in Range

. Range

- startIndex ..< endIndex

. So, for your example 0...0

stored as 0..<1

, which means the same thing.

For Swift 1.2 , you can use the global function contains

to check whether Int

to 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"
}

      

+4


source


Perhaps you could refer to the Half-Open Range Operator

 var myRange: Range<Int> = 0..<0

      



: "start Index 0 End Index 0"

The half-open range operator (a..<b)

defines a range that goes from a to b but does not include b. And the closed range operator (a...b)

will finally turn to(a..<b+1)

0


source


Since Range

it is also a collection, you can use its methods minElement()

and maxElement()

, which will return the correct index, observing a closed range ( ...

) or a half-open ( ..<

).

So the code below outputs zeros as expected:

let range: Range<Int> = 0...0
let min = range.minElement()!
let max = range.maxElement()!
print("min=\(min), max=\(max)")
// Output: "min=0, max=0"

      

Note: both methods have a complexity O(elements.count)

that may not be suitable in some cases.

0


source







All Articles