How to compare Range and DefaultBidirectio

2019-02-19 01:21发布

问题:

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?

回答1:

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


回答2:

As far as I know, String nor String.CharacterView does not have a concise method returning Range<String.Index> or something comparable to it.

You may need to create a Range explicitly with range operator:

let myStringContainsOnlyOneCharacter = myString.rangeOfComposedCharacterSequence(at: myString.startIndex)
    == myString.startIndex..<myString.endIndex

Or compare only upper bound, in your case:

let onlyOne = myString.rangeOfComposedCharacterSequence(at: myString.startIndex).upperBound
    == myString.endIndex