Swift TIL 3

Posted on 2020-06-24 16:38 +0100 in TIL • 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.