Swifty Switch

I've been gone from the blog for a while, not because I'm lazy (maybe a little bit), but because I just started a new job. I now work at Google as an iOS Software Engineer. I know, it's ironic, isn't it? Working for the company that creates Android, but work on the iOS app. :)

Anyway, with my new job, we decided that the app would be written entirely in Swift. That doesn't mean that everything that we write on top of would be Swift. For instance, Google has a whole bunch of internal libraries that we rely on, and all of them are Objective-C, as well as all of Foundation and UIKit.

Today I'm not going to talk about Objective-C and Swift interoperability, though that maybe a very interesting topic that I could write about in the future, but I wanted to talk about switch/case in Swift.

As you may have heard, Swift implements pattern matching in a very good way that you can actually use it for a lot of things. In this case, I want to show you a couple of things that I found interesting with Swift's switch/case.

Optional Binding

Switch statement in Swift has the ability to do optional binding, which means that it will safely unwrap the optional, and bind it to a variable, if the condition meets. Let's take a look at a snippet of code here:

let view: UIView = ...
switch (view) {
case let button = view as? UIButton:
    button.showsTouchWhenHighlighted = true
case let textField = view as? UITextField:
    textField.placeholder = "This is me"

As you can see above, if view is an instance of a UIButton class, the first case will get executed, and the variable button will be set. This is really nice because you can be sure that button is of type button, and even if view is an optional type (UIView?), we would still be sure that button is not nil.

I usually use this to cast variables to different types especially when I have a non-generic array type from Objective-C, or even a base type array such as an array of UIView.

Breaks not required

When you look at the above code, you'll see one thing missing from each case statement. There is no more break in each case statement, unless the case statement is empty. This is new in Swift, and could be unfamiliar to C/Objective-C developers. The question, though, is how is this going to work if you want to case to fall through. For instance, you may have code that handles 2 different enum values the same way. Swift introduces a keyword fallthrough to allow that. Let's take a look at an example.

These are some of the things that I found interesting about Swift's switch statement, and I hope you learn something from this posting. I'll be posting something soon, hopefully.

enum DownloadState {
    case: Unknown, None, Downloading, Downloaded

let state: DownloadState = ...
switch (state) {
case .Unknown:
    print("Unknown state")
case .None:
case .Downloading:
case .Downloaded:

In this case, if the variable state is .Unknown, the console output would be:

Unknown state