Swift
switch statement
comparison operators
programming
iOS development

Lesser than or greater than in Swift switch statement

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Swift, the switch statement offers a powerful way to control the flow of your code. Unlike some other programming languages, Swift's switch can handle more than just discrete values; it supports complex pattern matching including ranges and conditions utilizing less-than and greater-than comparisons. This article delves into how you can leverage these capabilities to write cleaner, more efficient Swift code.

The Basics of Swift Switch Statements

The switch statement in Swift is similar to that in other C-based languages but with enhanced capabilities:

  • Pattern Matching: Swift allows pattern matching, which means you can check for a range of values, specific cases, or even conditions.
  • No Implicit Fallthrough: Unlike switch statements in languages like C, Swift’s switch does not allow implicit fallthrough. Each case must be explicitly marked if it should continue to the next case.
  • Exhaustiveness: Swift ensures that all possible values are accounted for, which makes your code safer.

Using Less Than or Greater Than in Swift Switch

Swift's switch statement allows for complex pattern matching that includes less than (<) and greater than (>) conditions through the use of where clauses and range cases.

Using Ranges in Switch

You can use range operators such as ..< (half-open range) and ... (closed range) to match cases within specific bounds.

swift
1let score = 85
2
3switch score {
4case 0..<50:
5    print("Failing")
6case 50..<65:
7    print("Passing")
8case 65..<85:
9    print("Good")
10case 85...100:
11    print("Excellent")
12default:
13    print("Invalid score")
14}

In this example, the switch statement evaluates the score variable and matches it against various range conditions.

Using where Clauses

The where clause can be used in a switch statement for more fine-grained control when you need to apply conditions that aren't as simple as matching specific values or ranges.

swift
1let temperature = 30
2
3switch temperature {
4case let temp where temp < 0:
5    print("Freezing")
6case let temp where temp >= 0 && temp <= 15:
7    print("Cold")
8case let temp where temp > 15 && temp < 30:
9    print("Mild")
10case let temp where temp >= 30:
11    print("Hot")
12default:
13    print("Unexpected temperature")
14}

Here, the where clause helps apply more flexible conditions on the provided temperature value.

Combining Ranges and Conditions

Swift’s switch statements also allow combining ranges and where clauses for robust pattern matching.

swift
1let age = 23
2
3switch age {
4case 0..<13:
5    print("Child")
6case 13..<20:
7    print("Teenager")
8case 20..<30 where age != 25:
9    print("Young Adult")
10case 25:
11    print("Quarter Century milestone")
12default:
13    print("Adult")
14}

In this example, the young adult case is intended to match ages between 20 and 30 but excludes age 25 using the where clause.

Key Points Summary

Here's a table summarizing the key aspects of using the switch statement with less-than or greater-than conditions in Swift:

FeatureDescriptionExample
Range MatchingUse ..< and ... to define case rangescase 0..<50: for numbers less than 50
Where ClauseAdd conditions using where for fine-grained controlcase let x where x > 50: for numbers greater than 50
No Implicit FallthroughEach case is separate by default, promoting safer codeEach case must end with a break or execute a different control
ExhaustivenessAll possible values must be covered or handled with defaultProvides safer type handling

By including both range matching and conditional checks using where, Swift's switch statement becomes an indispensable tool for developers looking to write expressive, clear, and safe control flow in their applications. Whether you're checking a simple boolean condition or crafting more intricate logical rules, Swift's switch provides the mechanism you need. As with any powerful tool, the key lies in understanding its nuances and applying them judiciously.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.