Topics

#175: More Swift Tricks 🎩

Topics

Today we'll continue our look at interesting Swift features. Let's begin.

Multiple/Chained Optional Unwrapping

This is great when we've got multiple optionals to unwrap. We can even use unwrapped references from earlier in the statement in later parts of the statement. Neat!

if let URL = NSURL(string: someURL),
   let data = NSData(contentsOfURL: URL),
   let ship = Spaceship(data: data) {
    // use 'ship'
}

Multiple Initialization

We can initialize multiple references in one statement (and one line). This works for when using both let and var:

let ship1 = "Tantive IV", ship2 = "Ghost", ship3 = "Outrider"

Slicker Array Inits

We can simplify Array (and Dictionary) init statements like this:

let spaceships: [Spaceship] = []

To this:

let spaceships = [Spaceship]()

Semicolons: Gone but not forgotten!

Removing the need for trailing semicolons was one of Swift's most welcome features. However, they actually are present in Swift, and can serve a useful purpose. They'll let us write multiple statements on one line. This works great (for example) in guard statements:

guard let error == nil else { fail(error!); return }