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 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • I spent a while on this, so I’ll share my solution. I improved a gem to auto generate the constants.

    This creates easy accessors based off the enum like your method above. Then I extended UIStoryboard to make it easy to call them. Then for the prepare functions in segues I extended the UIStoryboardSegue object to allow comparisons against the generated constants. Looks nice.

    • Konstantin Koval

      I like your approach but with “if” you lose 1 important switch feature – exhausted check for handling all cases.

  • Nice way to keep all segues together. Thanks!

  • Mustafa Yusuf

    You can use this pattern all over in cocoa. For example you can create enum for all the entity names in core data model. Or you can create one for localization keys.

  • Pingback: Swift: Failable Enums with Optionals()