ProgrammingSwift Developer

How does pattern matching for ranges work in Swift and what features should be considered when implementing comparisons using switch?

Pass interviews with Hintsage AI assistant

Answer

In Swift, range matching is often used in switch-case for comparing values with ranges. The operators ..< (half-open range) and ... (closed range) are applied for this purpose:

let score = 76 switch score { case 0..<60: print("Unsatisfactory") case 60..<80: print("Satisfactory") case 80...100: print("Excellent") default: print("Incorrect value") }

Features:

  • Ranges must be increasing: from smaller to larger (otherwise the range will be empty).
  • Matching will be successful if the value lies within the range.
  • Since ranges are structures, they can be used for matching with any Comparable types.

Trick Question

What will happen if a range with an upper boundary that does not include the value (for example, 0..<5) is used in switch and the variable is equal to 5?

It is often answered that such a case will trigger, but this is incorrect: the operator ..< does not include the upper boundary. Example:

let value = 5 switch value { case 0..<5: print("0-4") case 5: print("five") default: print("other") } // Output: "five"

Real Error Examples Due to Ignorance of the Topic


Story

A developer implemented a display of user scores by ranges, using a closed range where the upper boundary was above the maximum possible value. This led to certain values falling into two intervals at once, causing the logic to work incorrectly.


Story

In an application, a switch-case was used with ranges where one of the values did not fit into any range due to incorrect usage of the operator (for example, 0...10 and 11...20 — and the value 10.5 did not fit anywhere). The bug was discovered only in production.


Story

In the service's code, dates were compared using range matching, using a half-open range incorrectly: the end date was not included, resulting in the exclusion of valid intervals, making it impossible to book the date on the last allowable day.