Buddybuild is a CI, CD and user feedback platform built for mobile development teams - sign up for free and start building better apps!

Topics

#170: Swift Tricks Revisited 🎩

Topics

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,
         .Crew,
         .Stormtroopers,
         .Planets: return .GET

    case .AddSpaceship,
         .AddCrewMember,
         .AddStormtrooper,
         .AddPlanet: return .POST

    case .RemoveSpaceship,
         .RemoveCrewMember,
         .RemoveStormtrooper,
         .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!