Topics

#159: Swift Shortcuts 💇

Topics

Today we'll begin checking out some syntactic niceties available in Swift. These are tricks that can help make our code more readable, and can often make it easier to reason about. Let's get started:

Omitting Types

The Swift type system is pretty great. As long as the compiler can infer the type, we can simply leave it out when calling static functions:

struct Theme {
  let titleColor: UIColor
  static let currentTheme = Theme(titleColor: .blackColor())
}

let nightMode = Theme(titleColor: .darkGrayColor())

This trick also works just as well for static properties:

let cell = ThemeTableViewCell(theme: .currentTheme)

Shorthand Argument Names

We can use a $x syntax to reference closure arguments:

spaceships.sort { $0.name > $1.name }

Trailing Closures

Many functions accept a closure as their last parameter:

func changeTheme(theme: Theme, completion: () -> ())

In these cases, we can call them with this shorter syntax:

Theme.changeTheme(dayMode) { /* */ }

Nil coalescing

The ?? operator offers us a way to express a sort of "fallback" relationship between two statements. When the first statement is nil, it "falls back" to the second.

let cellTitle = trooper.nickname ?? trooper.troopID

At a technical level this returns either an unwrapped optional, or the value on the right, which can't be an optional.