---
title: "#159: Swift Shortcuts 💇"
url: https://littlebitesofcocoa.com/159-swift-shortcuts
author: Jake Marsh
published: 2015-12-31
topics: ["Techniques","Swift"]
description: "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..."
---

# #159: Swift Shortcuts 💇

By Jake Marsh, December 31, 2015. HTML: https://littlebitesofcocoa.com/159-swift-shortcuts

Today we'll begin checking out some syntactic niceties available in _Swift_. These are tricks that can help make our code <i>more readable</i>, and can often make it <i>easier to reason about</i>. 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**:

``` swift
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**:

``` swift
let cell = ThemeTableViewCell(theme: .currentTheme)
```

## Shorthand Argument Names

We can use a `$x` syntax to reference **closure arguments**:

``` swift
spaceships.sort { $0.name > $1.name }
```

## Trailing Closures

Many **functions** accept a **closure** as their last **parameter**:

``` swift
func changeTheme(theme: Theme, completion: () -> ())
```

In these cases, we can call them with this shorter syntax:

``` swift
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.

``` swift
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**.
