Swift TIL 3

Posted on 2020-06-24 16:38 +0100 in TIL • Tagged with Swift, Apple • 1 min read

Today's little "Swift TIL" is observers. While reading up on the language I was delighted to find that it has observer support baked right into the language, for any sort of variable. So code like this:

var name  = "David" {

    willSet( new ) {
        print( "About to change name from \(name) to \(new)" )

    didSet( old ) {
        print( "Name changed from \(old) to \(name)" )

name = "davep"

Does what you'd imagine:

About to change name from David to davep
Name changed from David to davep

Not only can I see how that'd be useful for the main sorts of purposes that Swift is put to, I can think of many times when I'd have benefitted from that in my general day-to-day work. Of course, you can create an observer approach in any language really, but having an idiom that's part of the language feels nice and tidy.

Swift TIL 2

Posted on 2020-06-23 14:21 +0100 in TIL • Tagged with Swift, Apple • 1 min read

Following on with writing little notes to myself so I remember some key things as I learn about Swift...

I sort of feel like this will make reading code a little harder, so it's one I want to keep in mind. When calling an instance method, if it's not ambiguous, you can omit self. from the call. For example:

class Foo {
    private func inner() -> String { "Foo" }
    func outer() -> String { inner() + self.inner() }

print( Foo().outer() )

This makes me feel a little uneasy, and I strongly suspect I'll always use self. when writing such code: I'm a big fan of the idea that we write code for people, not for compilers.

Swift TIL 1

Posted on 2020-06-22 13:18 +0100 in TIL • Tagged with Swift, Apple • 1 min read

As I mentioned yesterday, I'm going to make a small series of posts where I write down things that I've stumbled on while getting to know Swift that are, for me personally, worthy of note, different, unusual, cool, or just simply "WTF!?!".

Because learning new stuff is fun.

My first one is that you can use keywords as identifiers if you "escape" them with backticks. Kind of like this:

let `let` = "let"

print( `let` )

I'm struggling to imagine a situation where I'd ever want to do this. I'm still unsure if my reaction is "that's cool" or "WTF?!?".