Less Gross Storyboard Segue to a Navigation Controller

This is a really ugly piece of code I’ve found myself writing in Swift whenever I’m preparing a storyboard segue where the destinationViewController is a UINavigationController whose root view controller is the thing I actually need to set properties on:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let viewController = (segue as? UINavigationController)?.topViewController {
        // Set up the view controller
    }
}

And so I decided to make this slightly less terrible by adding this category to my app:

extension UIStoryboardSegue {
    var navigationController: UINavigationController? {
        get {
            return destinationViewController as? UINavigationController
        }
    }
}

So now that ugly line becomes this:

if let viewController = segue.navigationController?.topViewController {
        // Set up the view controller
}