Hacker News new | ask | show | jobs
by ks2048 185 days ago
I think using "extended grapheme clusters" (EGC) (rather than code points or bytes) is a good idea. But, why not let you do "x[:2]" (or "x[0..<2]") for s String with the first two EGCs? (maybe better yet - make that return "String?")
3 comments

That's what I meant by "must be O(1)". I.e. constant time. String's Index type puts the non-constant cost of identifying a grapheme's location into the index creation functions (`index(_:offsetBy:)`, etc). Once you have an Index, then you can use it to subscript the string in constant time.

Like I said, you can easily extend String to look up graphemes by integer index, but you should define it as a function, not a subscript, to honor the convention of using subscripts only for constant-time access.

It's also just not a normal use case. In ten years of exclusive Swift usage, I've never had to get a string's nth grapheme, except for toy problems like Advent of Code.

Because that implies that String is a random access collection. You cannot constant-time index into a String, so the API doesn't allow you to use array indexing.

If you know it's safe to do you can get a representation as a list of UInt8 and then index into that.

I disagree. I think it should be indexed by bytes. One reason is what the other comment explains about not being constant-time (which is a significant reason), although the other is that this restricts it to Unicode (which has its own problems) and to specific versions of Unicode, and can potentially cause problems when using a different version of Unicode. A separate library can be used to deal with code points and/or EGC if this is important for a specific application; these features should not be inherent to the string type.
In practice, that is tiring as hell, verbose, awkward, unintuitive, requiring types attached to a specific instance for characters to do numeric indexing anyway and a whole bunch of other unnecessary ceremony not required in other languages.

We don't care that it takes longer, we all know that, we still need to do a bunch of string operations anyway, and it's way worse with swift than to do an equivalent thing than it is than pretty much any other language.

I don't think you can separate String from Unicode - that's what a "String" is in Swift.
In Swift (and in other programming languages) it does use Unicode, but I think it probably would be better not to be. But, even when there is a Unicode String type, I still think that it probably should not be grapheme clusters, in my opinion; I explained some of the reasons for this.