4 ms·
A String in Swift is a sequence of graphemes, unlike most languages which model strings as sequences of code points or just rawutf8, so there's no way to do eff
by slavapestov 9y ago
A String in Swift is a sequence of graphemes, unlike most languages which model strings as sequences of code points or just rawutf8, so there's no way to do efficient O(1) indexing. This is why the API is a bit more complex than you'd like.
- developer2 9y agoI keep getting this inaccurate answer of "they're just grapheme code points - you can't do it". That is why my example specifically used the .utf8 view. It's already possible to do exactly what I'm talking about, but it takes 4 complex lines of code, needing two calls to index() with startIndex/endIndex references and offsetBy arguments. The existing solution to this problem already uses integers (the offsetBy arguments)! I'm not talking about refactoring the String type, or breaking backwards compatibility. There would be no change in how the underlying String storage or access works. It's about adding a level of (zero overhead!) abstraction to simplify a common, basic operation. Every other language I've ever touched has easy to use substrings. It makes absolutely no sense that Swift requires assigning throwaway constants to represent the start and end indexes for a simple substring extraction. There's this level of superiority regarding the purity and correctness of Swift's String type that clouds developers' ability to see that there is no limitation to doing this. It blows my mind that the most modern major language is this clunky.