Swift TIL 3

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.
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.




