Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare Swift String.Index?

Tags:

swift

So I have an instance of Range<String.Index> obtained from a search method. And also a standalone String.Index by other means how can I tell wether this index is within the aforementioned range or not?

Example 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 do not work on String.Index instances, the only way seems to be to perform a loop through the string using advance but this seems overkill for such a simple operation.

like image 699
chakrit Avatar asked Oct 14 '25 16:10

chakrit


1 Answers

The beta 5 release notes mention:

The idea of a Range has been split into three separate concepts:

  • Ranges, which are Collections of consecutive discrete ForwardIndexType values. Ranges are used for slicing and iteration.
  • Intervals over Comparable values, which can efficiently check for containment. Intervals are used for pattern matching in switch statements and by the ~= operator.
  • Striding over Strideable values, which are Comparable and can be advanced an arbitrary distance in O(1).

Efficient containment checking is what you want, and this is possible since String.Index is 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

(For now, it seems that explicitly naming HalfOpenInterval is necessary, otherwise the ..< operator creates a Range by default, and Range doesn't support contains and ~= because it uses only ForwardIndexType.)

like image 94
jtbandes Avatar answered Oct 17 '25 07:10

jtbandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!