How must a `switch` statement handle enum cases?
iOS interview question for Intermediate practice.
Answer
A switch statement in Swift must handle all possible cases of an enumeration. If the enumeration is exhaustive (meaning it covers all possible states), no default case is strictly required. However, it's considered best practice to always include a default case for a few important reasons: Future-proofing: If you add new cases to your enumeration later, the compiler will warn you if your switch statement isn't handling them. Without a default case, the compiler might issue an error when new cases are added, which is exactly what we want in this case. Error handling: A default case allows you to gracefully handle unexpected values, preventing crashes or unexpected behavior. This makes your code more robust and easier to debug. Readability: A default case clarifies that the developer has thoughtfully considered the scenario of encountering values outside the explicitly defined enum cases. Code Example: swift enum Direction { case north case south case east case west } func describeDirection(direction: Direction) - String { switch direction { case .north: return "Heading north" case .south: return "Heading south" case .east: return "Heading east" case .west: return "Heading west" default: return "Unknown direction" } } Exhaustive Enums and Implicit Default Case: If an enum is marked with case for all possible values, Swift's type system will implicitly add a default handling for unmatched enum cases. The result is a compile time error if there's an unmatched case. This is beneficial for improved code quality and fewer runtime errors. Best Practices: Always strive to make your enums exhaustive by defining all possible cases. Include a default case in your switch statements, even with exhaustive enums, to handle potential future changes or unexpected values. This is for better error handling and code readability, which prevents silent failures. Use associated values with your enums to store additional data related to each case, making your code more expressive and flexible. Handle the default case appropriately. This may involve logging an error, throwing an error, or simply returning a default value, making your application behave more predictably.
Explanation
Swift's switch statements are more powerful than those in many other languages, offering pattern matching and exhaustive checking which results in a less error-prone code.