---
title: "#179: Swift Tricks: Properties 🎩"
url: https://littlebitesofcocoa.com/179-swift-tricks-properties
author: Jake Marsh
published: 2016-01-28
topics: ["Swift","Techniques"]
description: "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."
---

# #179: Swift Tricks: Properties 🎩

By Jake Marsh, January 28, 2016. HTML: https://littlebitesofcocoa.com/179-swift-tricks-properties

Today we'll look at [a](https://littlebitesofcocoa.com/164-swift-tricks) [couple](https://littlebitesofcocoa.com/170-swift-tricks-revisited) [more](https://littlebitesofcocoa.com/175-more-swift-tricks) 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**:

``` swift
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:

``` swift
lazy var couchPotatoes = [String]()
```

We can also use this technique to lazily init our UI elements, neat!

``` swift
lazy var someLabel: UILabel = {
  let label = UILabel()
  label.translatesAutoresizingMaskIntoConstraints = false
  label.font = UIFont(name: "AvenirNext", size: 20)
  return label
}()

```
