Swift - fatalError with Switch Statements

A quick write up of this because it was not obvious to find... it is not in The Swift Programming Language guide (at present), however you can find it in some of Apples sample code.

In Swift all switch statements must be exhaustive. To satisfy this requirement I had a default case, but based on the logic of how the program worked I knew that it should never be called.

In general in this situation it is a good idea to make sure we fail using an assert so that we will catch any problems during development.

func viewControllerForIndex(index: Int) -> UIViewController {
    switch index {
    case 0:
        return pastViewController
    case 1:
        return todayViewController
    case 2:
        return futureViewController
    default:
        assert(false, "Unexpected index")
    }
}

However, the switch statement was set up to return a value. So Swift was complaining that no value was being returned from the default case of the switch.

To sort this out it is possible to return a dummy value e.g. return UIViewController() or put an abort() after the assert().
Both of these solutions are messy as the extra line of code is extraneous.

This is where fatalError() comes in to play as it defined with the @noreturn attribute and so tells the compiler that the function does not return to its caller. So we can rewrite the method as:

func viewControllerForIndex(index: Int) -> UIViewController {
    switch index {
    case 0:
        return pastViewController
    case 1:
        return todayViewController
    case 2:
        return futureViewController
    default:
        fatalError("Unexpected index")
    }
}

Found anything useful as you investigate Swift?  Get in touch with Steve using Twitter (@StevenOglesby) or using the form below.

About Dr Steven Oglesby

Steven leads the technical team at the The Boffin Lab.

He has 20 years experience in the software industry, haven taken the lead developer role a number of large financial systems.  Prior to his software career he achieved a PhD in Particle Physics working on the Large Hadron Collider at CERN.

Steven's our lead developer and is happiest coming up with simple solutions to the hardest technical problems.  Like all the team he wants to make the best products he can so he's always looking for innovations that can push us forward.

Outside work Steven is runner, currently chasing a new marathon PB when he's not chasing after his family.

Find him online

   

Dr Steven Oglesby