Swift TIL 3

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.

Comments (2)

Syed Fazle Rahman's photo

Hi Dave Pearson, these TIL posts are great! I read them all. Keep them coming. 🍺

Dave Pearson's photo

Developer, Emacs addict, geek. Hangs out with bioinformaticians as his day job.

That's very kind of you to say so, thank you. Hoping to write up a single little thing I've discovered each day, as time allows. If nothing else it should help me remember these things. :-)