Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDK. Save $177 with coupon code LBOC.


#170: Swift Tricks Revisited 🎩


Today we'll look at a few more interesting Swift tips and tricks. Let's get started.

Multiple Switch Cases

We'll start with a simple one. We can simplify messy switch statements by combining the similar cases. This is similar to how we can use multiple case statements in other languages, but a bit less wordy:

extension FirstOrderAPI {
  var method: HTTPMethod {
    switch self {
    case .Spaceships,
         .Planets: return .GET

    case .AddSpaceship,
         .AddPlanet: return .POST

    case .RemoveSpaceship,
         .DestroyPlanet: return .DELETE

Operator Parameters

We can actually pass literal operators in as a parameter, for example:

[1, 2, 3, 4].reduce(0, combine: +)

This works because the + operator is actually a function under the hood:

public func +(lhs: Int, rhs: Int) -> Int

Simpler Reuse Identifiers

In Objective-C, It's quite common to use NSStringFromClass to use a cell's class name as it's reuseIdentifier. In Swift though:

let reuseIdentifier = String(SpaceshipTableViewCell)

Shout out to Natasha for pointing this one out!