Vamos
Vamos

Reputation: 2801

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?

Upvotes: 3

Views: 6988

Answers (2)

youngermann
youngermann

Reputation: 1

From Foundation:

    extension NSString : ExpressibleByStringLiteral {

        /// Create an instance initialized to `value`.
        required public convenience init(stringLiteral value: StaticString)

        /// A type that represents a string literal.
        ///
        /// Valid types for `StringLiteralType` are `String` and `StaticString`.
        public typealias StringLiteralType = StaticString

        /// A type that represents an extended grapheme cluster literal.
        ///
        /// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,
        /// `String`, and `StaticString`.
        public typealias ExtendedGraphemeClusterLiteralType = StaticString

        /// A type that represents a Unicode scalar literal.
        ///
        /// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,
        /// `Character`, `String`, and `StaticString`.
        public typealias UnicodeScalarLiteralType = StaticString
    }

So it seems ExtendedGraphemeClusterLiteral and UnicodeScalarLiteral are just StaticString

Upvotes: 0

Marcus
Marcus

Reputation: 2321

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.

Upvotes: 7

Related Questions