Swift Switch Statement and Cases Example

1. Introduction

The Swift programming language offers a powerful and expressive switch statement, which allows for intricate pattern matching and concise control flow. Unlike other languages where switch can only test for equality, Swift's switch is capable of matching a wide range of conditions.

2. Source Code Example

// Define an enum to represent some basic weather conditions
enum Weather {
    case sunny, cloudy, rainy, snowy

// A simple function to offer suggestions based on the weather
func outfitSuggestion(for weather: Weather) {
    switch weather {
    case .sunny:
        print("Wear a t-shirt and sunglasses!")
    case .cloudy:
        print("Maybe carry a light jacket!")
    case .rainy:
        print("Don't forget an umbrella!")
    case .snowy:
        print("Wear a heavy coat and boots!")

// Another example: switch with ranges
let temperature = 23
switch temperature {
case ..<0:
    print("It's freezing cold!")
case 0...10:
    print("It's pretty cold!")
case 11...20:
    print("It's a bit chilly!")
case 21...30:
    print("It's nice and warm!")
    print("It's really hot!")

// Calling the function
outfitSuggestion(for: .rainy)


It's nice and warm!
Don't forget an umbrella!

3. Step By Step Explanation

1. We start by defining an enum called Weather that represents various weather conditions.

2. The outfitSuggestion(for:) function takes a Weather enum value as its parameter. Inside, we use the switch statement to match the provided value with each potential weather condition and print an outfit suggestion based on the match.

3. Following that, we showcase how switch can be used with ranges. We declare a temperature constant and use the switch statement to match its value against various temperature ranges. This demonstrates the versatility of Swift's switch, allowing for more than just equality checks.

4. Finally, we call the outfitSuggestion(for:) function and provide .rainy as the argument, which prints an outfit suggestion for rainy weather.

The switch statement in Swift provides a clean and efficient way to handle multiple conditions, making it a valuable tool for developers to manage control flow with clarity and precision.