Making Strings Integer-Subscriptable

With the introduction of strings as collections in Swift 4, you no longer have to call characters on a string to get the array of characters which comprise the string.

However, if you have tried to do something like someString[0..<5] you may have encountered this error message: 'subscript' is unavailable: cannot subscript String with a CountableRange<Int>, see the documentation comment for discussion

This is because the subscript on Stringexpects a String.Index and not an integer.   To remedy this we can create an extension on String which allows ranges of integers.

Here we allow String to accept an integer range and we compute the indices using the lowerbound and upperbound offsets of Range.

and sure enough if we try it out, we get the correct substring.

However Swift has many different types of ranges.  We have PartialRangeFrom, PartialRangeUpTo, PartialRangeThrough, and ClosedRange. We can similarly extend all of these in String.  So this is what the final extension on String looks like.

now you can do all sorts of things like

hopefully you have enjoyed this short but sweet post.   There is a more extensive one on strings coming soon.   Stay tuned.