This is the English version of my post at cnblogs.com.

A Question

Given the code bellow:

1
2
3
4
5
struct Book {
    let name: String
}

let book: Book = "Charlotte's Web"

Is there a way to make it work?

So, is there a way to implicitly create a struct from a string literal?

Expressible Literal Protocol

The answer is yes, with the the magic of expressible literal protocol. It’s a suite of protocols which includes:

protocolliteral
ExpressibleByNilLiteralnil
ExpressibleByBooleanLiteralboolean literal
ExpressibleByIntegerLiteralinterger literal
ExpressibleByFloatLiteralfloat literal
ExpressibleByUnicodeScalarLiteralunicode scalar literal
ExpressibleByExtendedGraphemeClusterLiteralextended grapheme cluster literal
ExpressibleByStringLiteralstring literal
ExpressibleByStringInterpolationinterpolated string literal
ExpressibleByArrayLiteralarray literal
ExpressibleByDictionaryLiteraldictionary literal

In this case, adding ExpressibleByStringLiteral conformance can make the implicit instantiation possible.

1
2
3
4
5
extension Book: ExpressibleByStringLiteral {
    init(stringLiteral value: String) {
        self.init(name: value)
    }
}