Switch Statements

Refactor comparison-heavy and nested if statements to switch statements where possible. Good targets of opportunity include series of conditions based on the same variables. For example, the following code checks for variations of condition1 and condition2 truth values. This flow can easily be refactored to switch. Each condition is basically matching against the same pattern:

 if​ condition1 && condition2 { ​// no
  ...
 } ​else​ ​if​ condition1 && !condition2 {
  ...
 } ​else​ ​if​ !condition1 && condition2 {
  ...
 } ​else​ { ​// or !condition1 && !condition2
 // or !(condition1 || condition2)
  ...
 }

A tuple-based switch statement creates an easy-to-inspect list. It transforms the complex snaky flow of the preceding ...

Get Swift Style 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.