Search code examples
swiftswift3

What is a GraphemeCluster and what does ExpressibleByExtendedGraphemeClusterLiteral do?


While looking into the documentation for ExpressibleByStringLiteral I came across ExpressibleByExtendedGraphemeClusterLiteral. While I understand that implementing the former allows the use of string literals to initialise something other than the String type, I'm not sure what the latter is used for.

In fact, after some searching, I'm not sure what a grapheme cluster is - can someone explain what it is, and also, how it relates to the protocol, what functionality does this provide if implemented?


Solution

  • A grapheme cluster is a collection of symbols that together represent an individual character that the user will see within a string on the screen. It generally comprises a "base character" plus what Apple calls "combining marks", and are used, for instance, when there is no available precomposed single Unicode character that might do the job for you.

    When grapheme clusters are used in strings you have to take special care that any functions looking for substrings etc. are able properly to demarcate the boundaries between clusters.

    You can see several examples here:

    https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

    Compliance with the protocol ExpressibleByExtendedGraphemeClusterLiteral simply means that the character in question can be initialised with a literal grapheme cluster. Again, you can see examples of this in te above link.