Swift TIL 6

Posted on 2020-06-27 21:23 +0100 in TIL • 1 min read

I'm going to file this one under "it seems really unnecessary, but it's also kinda cool". While reading up about protocols the book I'm reading introduced the ExpressibleBy*Literal protocols, where the * is one of a number of obvious literals. For example: ExpressibleByStringLiteral. As you might imagine, it lets you create a class that can be initialised with a literal value, as opposed to needing to appear to call the constructor for a class.

So, for a silly example:

class Hello : ExpressibleByStringLiteral {

    private let what : String

    required init( stringLiteral what : String ) {
        self.what = what
    }

    func say() {
        print( "Hello, \(self.what)!" )
    }
}

You could, of course, write this:

let v1 = Hello( "world" )
v1.say()

but because of ExpressibleByStringLiteral you can also write:

let v2 : Hello = "universe"
v2.say()

Now, sure, in this case it saves you nothing, but this does also mean that parameters of functions whose type uses one of the `ExpressibleBy*Literal protocols can be passed a literal, rather than a "long-hand" instantiated object. For example:

func Greet( _ h : Hello ) {
    h.say()
}

Greet( "davep" )

I can see that being quite handy.