3 ms·
>> support for creating, using and managing substrings Can I finally extract a substring from the middle of a string using integer offsets, in one line? Someth
by developer2 9y ago
>> support for creating, using and managing substrings
Can I finally extract a substring from the middle of a string using integer offsets, in one line? Something like string.utf8.substr(3, 5)?
Or does it still take an absolutely insane and unacceptable 4 lines of code with throwaway temp variables to track the start and end indexes? The inability to do basic string manipulations is a major turnoff, to the point it makes the entire language look like a bad joke.
- fauigerzigerk 9y agoYou could do something like String(s.dropFirst(3).prefix(5))
- slavapestov 9y agoA 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.