iOS: Working with Segues in Swift

UPDATE: This no longer works as of XCode 6.1 / Swift 1.1. Read the updated blog post here.

I love how easy Swift makes it to encapsulate small pieces of information compared to Objective-C. With tuples, enums, and structs, code becomes a lot more readable. I got reminded of this just yesterday, when @nickoneill showed an example of how to use enums to work with Segue Identifiers at the Swift Hack Day.

Let’s say you have three different segues from one view controller:

Segue Three View Controllers

Using Swift enums, your ViewController’s segue logic can now look like this!

import UIKit

class ViewController: UIViewController {

    enum SegueIdentifier: String {
        case SegueToRedViewIdentifier = "SegueToRedViewIdentifier"
        case SegueToGreenViewIdentifier = "SegueToGreenViewIdentifier"
        case SegueToBlueViewIdentifier = "SegueToBlueViewIdentifier"
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        if let segueIdentifier =  SegueIdentifier.fromRaw(segue.identifier) {
            
            switch segueIdentifier {
            case .SegueToRedViewIdentifier:
                println("red")
            case .SegueToGreenViewIdentifier:
                println("green")
            case .SegueToBlueViewIdentifier:
                println("blue")
            }
        }
    }

}

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.