In Swift, the switch statement supports extended pattern matching: you can use where to add conditions to individual cases. This allows you to implement complex business logic and filtering.
Example:
enum Person { case student(score: Int) case teacher(specialty: String) } let people = [Person.student(score: 95), Person.teacher(specialty: "Math"), Person.student(score: 65)] for person in people { switch person { case .student(let score) where score > 90: print("Straight A student with a score of \(score)") case .teacher(let specialty): print("Teacher of: \(specialty)") default: print("Other case") } }
Using where improves readability and avoids code duplication, but overly complex conditions can hinder maintainability, and pattern matching with associated values requires strict control over the order of cases.
Question: "Is it necessary to use uniquely named variables in each case when pattern matching with where inside switch?"
Answer: No, but it is recommended to avoid confusion. If the same variable names are used in different cases, the context will be limited to the corresponding case, but the same name can complicate readability and code maintenance.
Example:
switch value { case .status(let code) where code == 200: print("OK") case .status(let code) where code == 404: print("Not found")
Story 1
In a banking application, there was a status analysis section with several where conditions. Due to a missing break and the incorrect order of cases, a situation occurred where a specific case was not handled, and users did not see the full status of transactions. The error was discovered only during field testing.
Story 2
In the authorization system, a developer used the same variable names in different cases, which led to confusion and a bug: in the second case, they tried to use a variable defined in another case. The build worked, but incorrectly in certain scenarios.
Story 3
In complex pattern matching with where, it was not taken into account that default would not handle part of the combinations of the associated enum, causing the application to crash with a pattern matching failed error. The problem was noticed only when integrating new data types in the future.