Subscripting in String extension to access substrings and characters with Int types

FWIW, this thread hasn't really mentioned two high-level reasons why this problem isn't been solved yet:

  1. It favors indexing from the beginning of the string, but people [edit:] also want to be able to use integers that index from the end instead. (That is, where 0 represents the end of the string.) No one has come up with syntax for this that pleases a majority of people.

    This is perhaps not a strong argument "against". It might be worth doing start-relative indexes only, but you'd probably need to make a convincing argument "for".

  2. There really aren't a lot of general use cases that need Int-based indexing into strings. For example:

    let cadena = "A long time ago in a galaxy far far away"
    cadena[5...25]

What is the actual use case for getting the substring "g time ago in a galax", as in the above code?

Usually, if you have a string that you really want to treat as an array of characters, you should probably create an Array<Character>.

Or, if you have a string that has some kind of internal structure based on substrings of known length, it may be better to split the string at those boundaries once, then work with the substrings. In that case, the "ugly" String.Index-based code isn't nearly as much a problem as it might seem.

This isn't to say you're wrong, just a larger perspective, on a topic that has already been debated, at length, a number of times in these forums.

6 Likes