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 might 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access