How do I compare Swift String.Index?

So I have an instance Range<String.Index>

obtained from a search method. And also standalone in String.Index

other ways, how can I tell if this index is within the above range or not?

Sample code:

let str = "Hello!"

let range = Range(start: str.startIndex, end: str.endIndex)
let anIndex = advance(str.startIndex, 3)

// How to tell if `anIndex` is within `range` ?

      

Since comparison operators don't work on instances String.Index

, the only way is to loop through the string with advance

, but that seems overkill for such a simple operation.

+3


source to share


1 answer


Beta 5 Release Notes:

The range idea has been split into three distinct concepts:

  • Ranges, which are collections of sequential discrete values ForwardIndexType

    . Ranges are used for slicing and iteration.
  • Intervals above values Comparable

    that can effectively test containment. Intervals are used to match patterns in the operator and operator switcher ~=

    .
  • Moving through values Strideable

    that are comparable and can be moved an arbitrary distance in O (1).

An effective containment check is what you want and it is possible because String.Index

- Comparable

:



let range = str.startIndex..<str.endIndex as HalfOpenInterval
// or this:
let range = HalfOpenInterval(str.startIndex, str.endIndex)

let anIndex = advance(str.startIndex, 3)

range.contains(anIndex) // true
// or this:
range ~= anIndex // true

      

(At the moment it seems like the name is explicitly specified HalfOpenInterval

, otherwise the operator ..<

creates by default Range

, Range

not support contains

and ~=

because it only uses ForwardIndexType

.)

+5


source







All Articles