#179: Swift Tricks: Properties 🎩


Today we'll look at a couple more tips for working in Swift. This time, we'll focus on Swift properties. Let's dive in.

Property Observers

In Objective-C, we'd likely use Key-Value Observing to "know" when the value of a property on one of our objects changes.

KVO still works great in Swift. In many cases, we might be able to get away with Swift's (much cleaner) property observers:

struct Spaceship {
  let name: String

  var currentSpeed: Int = 0 {
    willSet { print("About to change speed to \(newValue)") }
    didSet {
      if currentSpeed > oldValue {
        print("Increased speed to \(currentSpeed)")
      } else if currentSpeed < oldValue {
        print("Decreased speed to \(currentSpeed)")

Lazy Properties

"Lazy" initialization is a great way to put off expensive work until some later time in our code. Back in Objective-C, if we wanted to "lazily" initialize a property, we might go override it's getter, and check if a private instance variable is nil or not, then populate it if it's not, then return it. Whew!

In Swift, we can forget all of this and accomplish the exact same with a simple new keyword:

lazy var couchPotatoes = [String]()

We can also use this technique to lazily init our UI elements, neat!

lazy var someLabel: UILabel = {
  let label = UILabel()
  label.translatesAutoresizingMaskIntoConstraints = false
  label.font = UIFont(name: "AvenirNext", size: 20)
  return label