Skip to main content

Command Palette

Search for a command to run...

Swift TIL 6

Published
•2 min read•View as Markdown
Swift TIL 6
D

Initially self-taught back in the early 1980s, I started programming on a ZX81 and I've been in love with software development ever since. My "primary" language has drifted over the years, but as it has I've made an effort to get to know and work with plenty of others.

These days I do a lot of Python/Django/JavaScript work, while having fun working with bioinformaticians and machine learning scientists.

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.

5 views

More from this blog

davep

37 posts

Developer http://davep.dev, Emacs addict http://elisp.dev, geek.

Hangs out with bioinformaticians.