---
title: "#180: More Swift Tricks 🎩"
url: https://littlebitesofcocoa.com/180-more-swift-tricks
author: Jake Marsh
published: 2016-01-29
topics: ["Swift","Techniques"]
description: "Today we'll continue our look at interesting Swift features. Let's begin. Try as we might, sometimes still we end up with an AnyObject or Any reference in..."
---

# #180: More Swift Tricks 🎩

By Jake Marsh, January 29, 2016. HTML: https://littlebitesofcocoa.com/180-more-swift-tricks

Today we'll [continue](https://littlebitesofcocoa.com/179-swift-tricks-properties) [our](https://littlebitesofcocoa.com/175-more-swift-tricks) [look](https://littlebitesofcocoa.com/170-swift-tricks-revisited) [at](https://littlebitesofcocoa.com/164-swift-tricks) interesting _Swift_ features. Let's begin.

## Type Matching with ‘is’

Try as we might, sometimes still we end up with an `AnyObject` or `Any` reference in our **Swift** code. We can ask if it `is` a given **type** or **subtype** using **Swift's** powerful **pattern matching**:

``` swift
protocol Vehicle { }
struct Spaceship : Vehicle { }

let thing: Any = Spaceship()

if thing is Vehicle { print("let's move") }
else { print("can't move") }
```

## Parsimonious Declarations

Hat tip to [Erica Sadun](http://ericasadun.com/2015/11/04/5-delicious-tuple-tricks-in-swiftlang/) for passing along this one. We can use a sort of <i>Tuple-ish</i> syntax to create a bunch of related **references** inline:

``` swift
var (top, left, width, height) = (0.0, 0.0, 100.0, 50.0)
spaceship.width = width
```

## Inline Closures

This technique has a few different applications, but one good example is capturing a **value** from a `switch` **statement** inline:

``` swift
enum Theme {
  case Day, Night, Dusk, Dawn

  func apply() {
    // ...

    let backgroundColor: UIColor = {
      switch self {
        case Day: return UIColor.whiteColor()
        case Night: return UIColor.darkGrayColor()
      }
    }()

    // ... set backgroundColor on all UI elements
  }
}
```
