glenstorey glenstorey - 6 months ago 32
Swift Question

Is String.substringWithRange in bounds?

I'm having a problem with non-latin character sets, and I need to check that a Range is in bounds before performing .substringWithRange. This seems really easy, but I can't find the way to do this.

Given a range:

let lastCharRange = currentString.endIndex.predecessor() ..< currentString.endIndex

How can I check:

let lastExpected = expectedString.substringWithRange(lastCharRange)

is in bounds?


Indexes are tied closely to the String that generated them -- actually to the String's CharacterView, which is a CollectionType. This holds true generally for collections.

So, you simply can't use the Index you got from one String on another String.

Depending on what you are doing, you might have to get a substring from the first and then search the second. You can also get the two Strings' CharacterViews and work with them via their collection-based interface: expectedString.characters.last, for example.