Swift Substring Slicing

I was toying around with the ‘Natural Language’ Framework for iOS when I got a warning about a deprecated line.


fromString.substring(with: tokenRange)

Code screenshot showing warning

substring(with:) is deprecated: Please use String slicing subscript.

This produced the warning: substring(with:) is deprecated: Please use String slicing subscript.

I looked up the new docs on String slicing and it looked as though I could just put the range in brackets and get what I wanted.


I thought, hey this is easy.


But that produced a hard error: Subscript ‘subscript(_:)’ requires the types ‘String.Index’ and ‘Int’ be equivalent.

I broke out the range into its lower and upper bounds. It gave the same error.


I printed out the type and it showed Subscript. Of course, it was the wrong type. These substring methods are very interesting and are basically just a reference to the original String. There is even a warning on the Apple docs for Substring.

Don’t store substrings longer than you need them to perform a specific operation. A substring holds a reference to the entire storage of the string it comes from, not just to the portion it presents, even when there is no other reference to the original string. Storing substrings may, therefore, prolong the lifetime of string data that is no longer otherwise accessible, which can appear to be memory leakage.

So I actually just needed to cast it into a String from that Substring:


So, for my purposes:

wholePoem.substring(with: tokenRange)
Just needed to be rewritten to this:

Here is a playground showing this.