---
title: "#257: Property Observers on Local Variables 🐤"
url: https://littlebitesofcocoa.com/257-property-observers-on-local-variables
author: Jake Marsh
date: 2016-08-31
published: 2016-08-31
topics: ["Swift"]
description: "We first looked at Swift's property observers back in Bite #179. They're a great way to know when a property's value is about to change, or just finished..."
---

# #257: Property Observers on Local Variables 🐤

By Jake Marsh, August 31, 2016. HTML: https://littlebitesofcocoa.com/257-property-observers-on-local-variables

We first looked at Swift's _property observers_ back in [Bite #179](https://littlebitesofcocoa.com/179). They're a great way to know when a **property's value** is about to change, or just finished changing.

Traditionally, they look like this:

``` swift
class Spaceship : NSObject {
  var name: String {
    didSet { print(name) }
  }
}
```

Nothing too fancy here, just printing the latest **value** for **name**, anytime a **ship's name** changes.

This works great for **properties** on **types**, but it turns out we can actually use these same _observers_ on **local variables** as well:

``` swift
var name = "Tim Cook" {
  didSet { print(name) }
}

name = "Eddy Cue"
name = "Craig Federighi"
```

This prints:

``` text
Eddy Cue
Craig Federighi
```

Neat!

[Kelan Champagne](http://kelan.io/2016/swift-didset-on-local-variables/) mentions an interesting technique for super-simple value-change tracking:

``` swift
var previousStatuses = [String]()
var awayMessage: String? = nil {
  willSet {
    guard let awayMessage = awayMessage else { return }
    previousStatuses.append(awayMessage)
  }
}

awayMessage = "out to lunch, brb"
awayMessage = "eating dinner"
awayMessage = "emo song lyrics"
awayMessage = nil

print("Previous: ", previousStatuses)
```

This prints:

```Previous: ["out to lunch, brb", "eating dinner", "emo song lyrics"]```

This technique might not make sense in many situations, but is a nice feature to know about in case we can ever benefit from it.

A huge thanks to both [Kelan Champagne](http://kelan.io/2016/swift-didset-on-local-variables/) and [Chris Eidhof](http://chris.eidhof.nl/post/structs-and-mutation-in-swift/) for pointing this out!
