Manuel Manuel - 2 months ago 14
Swift Question

How to compare Range<String.Index> and DefaultBidirectionalIndices<String.CharacterView>?

This comparison worked in Swift 2 but doesn't anymore in Swift 3:

let myStringContainsOnlyOneCharacter = mySting.rangeOfComposedCharacterSequence(at: myString.startIndex) == mySting.characters.indices


How do I compare Range and DefaultBidirectionalIndices?

Answer

From SE-0065 – A New Model for Collections and Indices

In Swift 2, collection.indices returned a Range<Index>, but because a range is a simple pair of indices and indices can no longer be advanced on their own, Range<Index> is no longer iterable.

In order to keep code like the above working, Collection has acquired an associated Indices type that is always iterable, ...

Since rangeOfComposedCharacterSequence returns a range of character indices, the solution is not to use indices, but startIndex..<endIndex:

myString.rangeOfComposedCharacterSequence(at: myString.startIndex) 
== myString.startIndex..<myString.endIndex
Comments