switch vs. if/else

switch statements are primarily useful for comparing a value against a number of potentially matching cases. if/else statements, on the other hand, are better used for checking against a single condition. switches also offer a number of powerful features that allow you to match against ranges, bind values to local constants or variables, and match patterns in tuples – to name just a few features covered in this chapter.

Sometimes you will be tempted to use a switch statement on a value that could potentially match against any number of cases, but you really only care about one of them. For example, imagine checking an age constant of type Int looking for a specific demographic: ages 18-35. You might think writing ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.