Topics

#184: More Swift Tricks 🎩

Topics

Today we'll continue our look at Swift tips and tricks. Let's dive in.

Nested Types

We'll begin with an organizational tip. We can nest our type declarations inside one another to group related definitions:

enum CostumeDepartment {
  case Day, Night

  struct Color { /* ... */ }
  struct Image { /* ... */ }
  struct Text { /* ... */ }

  func appLogoImage() -> Image { /* ... */ }
}

Swift's compiler is smart enough to take note of this nesting whenever ambiguity arises. This means we can use types nested inside multiple "container" types without any issues.

Even-lazier Lazy Definitions

We covered the lazy keyword in Bite #179. It turns out, we can be even lazier, and omit the extra closure altogether. (Still works the same).

lazy var backgroundView = SpecialBackgroundView()

Variadic Parameters

Objective-C supported these as well, but they were a bit of pain to work with there. In Swift, we simply add an ellipsis (...) to our function's definition, and we receive the arguments as a strongly-typed Swift** array**.

func sum(numbers: Int...) -> Int {  
  var total = 0
  for number in numbers { total += number }
  return total
}

...or if we wanted to write that function in an even Swiftier way:

func sum(numbers: Int...) -> Int { return numbers.reduce(0, combine: +) }