Many Swift users, especially users who are familiar with syntaxes like str[3:6]
or any equivalent notation in other languages, are hoping for a simpler indexing and slicing API. We have seen many attempts in this forum.
Can you explain why you find the former more readable, simple, or efficient?
Because it has less punctuation and is easier to parse for the human eye. This does not invalidate the rest of your answer. Yes, prefix
comes with known behavior. The ad-hoc length
does not. And length
is used in too many contexts: it is difficult to load it with the same efficiency as prefix
.
This is because Swift String does not conform to the RandomAccessCollection protocol, the protocol that guarantees "efficient random-access index traversal".
String elements are Character, a not-so-trivial type whose values can be A, É, 㞛, or complex emojis like
. There are many ways to store characters in memory, and the current trend is to store them in a variable-width encoding (in Swift 5, UTF8 is the preferred one). Because of those variable-width encodings, and other Unicode subtleties, jumping to the 10th character of a string forces your to iterate through all the 9 previous ones. Accessing the Nth element of a String is not a cheap O(1) operation as in Array, but a linear, O(N) operation. This is why String can't adopt RandomAccessCollection.
And this is also why we don't have str[10]
. The designers of the Standard Library did not want a potentially costly operation to look like it is cheap. For the same reason, we don't have str[3:6]
. And it's likely we will never have it until the Core Team radically changes its mind.
Note that there exists many third-party libraries out there that extend the standard library with such convenience accessors. You can use them. But they may make your code not efficient (it will run fine with small inputs, and become surprisingly slow with slightly longer inputs). It's a very common mistake.
It has been years now that many people have been looking for improvements in the Swift standard library in order to soothe some pain points
Previous discussions are fascinating, but be prepared: it's a long read!