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

这一生的挚爱 提交于 2019-12-19 09:24:40

问题


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


来源:https://stackoverflow.com/questions/39533523/how-to-compare-rangestring-index-and-defaultbidirectionalindicesstring-charac

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!