Topics

#180: More Swift Tricks 🎩

Topics

Today we'll continue our look at 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:

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 for passing along this one. We can use a sort of Tuple-ish syntax to create a bunch of related references inline:

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:

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
  }
}