Swift Tutorial

Swift Data Types

Swift Control Flow

Swift Functions

Swift Collections

Swift OOPs

Swift Additional Topics

Swift-Switch Statement

In Swift, the switch statement is a powerful and flexible control flow structure that allows you to choose between multiple possible cases based on the value of an expression. It provides a more clear and expressive way to control the flow of your program compared to a series of if-else statements.

Here's a basic overview of the switch statement:

Basic Syntax:

switch expression {
case value1:
    // code to execute for value1
case value2:
    // code to execute for value2
// additional cases as needed
default:
    // code to execute if no case matches
}

Simple Example:

let fruit = "apple"

switch fruit {
case "banana":
    print("It's a banana.")
case "apple":
    print("It's an apple.")
default:
    print("Unknown fruit.")
}
// Outputs: "It's an apple."

Key Features and Characteristics:

  • No Implicit Fallthrough: Unlike some other languages, Swift doesn't allow cases to fall through to subsequent cases by default. Each case must contain executable code or an explicit break statement.
switch fruit {
case "banana":
    print("It's a banana.")
case "apple":
    print("It's an apple.")
    break  // this is not necessary here because Swift doesn't fall through
default:
    print("Unknown fruit.")
}
  • Multiple Values: You can match multiple values in a single case:
switch fruit {
case "banana", "apple":
    print("It's either a banana or an apple.")
default:
    print("Unknown fruit.")
}
  • Interval Matching: Swift allows value intervals in case:
let age = 25

switch age {
case 0...12:
    print("Child.")
case 13...19:
    print("Teenager.")
case 20...59:
    print("Adult.")
default:
    print("Senior.")
}
// Outputs: "Adult."
  • Tuples and Value Bindings: You can match against tuples and bind variable or constant names to tuple elements:
let coordinate = (x: 3, y: 4)

switch coordinate {
case (0, 0):
    print("Origin")
case (let x, 0):
    print("On the x-axis at x=\(x)")
case (0, let y):
    print("On the y-axis at y=\(y)")
default:
    print("Somewhere else.")
}
// Outputs: "Somewhere else."
  • where Clause: You can specify additional conditions using a where clause:
switch coordinate {
case let (x, y) where x == y:
    print("On the line x=y")
case let (x, y) where x == -y:
    print("On the line x=-y")
default:
    print("Somewhere else.")
}
  • Complex Types: You're not limited to simple types like numbers and strings. You can use switch with enums, structs, and classes as well.

Remember, Swift requires the switch statement to be exhaustive. If you don't handle every possible value in the cases, you must provide a default case to catch any unhandled values. This requirement ensures that you consciously make a decision about every possible value, leading to more predictable and safer code.

  1. How to use switch statement in Swift:

    Description: The switch statement in Swift allows you to evaluate a value against multiple possible matching patterns.

    let day = "Monday"
    
    switch day {
    case "Monday":
        print("It's Monday!")
    case "Tuesday":
        print("It's Tuesday!")
    default:
        print("It's another day of the week.")
    }
    
  2. Handling multiple cases with switch in Swift:

    Description: You can handle multiple cases with a single block of code in a switch statement.

    let fruit = "Apple"
    
    switch fruit {
    case "Apple", "Pear":
        print("It's an apple or pear.")
    case "Banana":
        print("It's a banana.")
    default:
        print("It's something else.")
    }
    
  3. Swift switch statement with range and intervals:

    Description: You can use ranges and intervals in a switch statement to match values within a specified range.

    let score = 85
    
    switch score {
    case 0..<60:
        print("Failed")
    case 60..<80:
        print("Pass")
    case 80...100:
        print("Excellent")
    default:
        print("Invalid score")
    }
    
  4. Switch statement with patterns in Swift:

    Description: Swift allows pattern matching in switch statements for more expressive matching.

    let point = (2, 2)
    
    switch point {
    case (0, 0):
        print("Origin")
    case (_, 0):
        print("On x-axis")
    case (0, _):
        print("On y-axis")
    case (-2...2, -2...2):
        print("Inside the square")
    default:
        print("Outside the square")
    }
    
  5. Using fallthrough in Swift switch cases:

    Description: fallthrough is used to fall through to the next case in a switch statement.

    let number = 3
    var description = "The number is "
    
    switch number {
    case 1:
        description += "One. "
        fallthrough
    case 2:
        description += "Two. "
        fallthrough
    case 3:
        description += "Three."
    default:
        description += "Another number."
    }
    
    print(description)
    
  6. Matching enum cases with switch in Swift:

    Description: switch statements work well with enums, allowing you to match enum cases.

    enum Direction {
        case north, south, east, west
    }
    
    let currentDirection = Direction.east
    
    switch currentDirection {
    case .north:
        print("Going north")
    case .south:
        print("Going south")
    case .east:
        print("Going east")
    case .west:
        print("Going west")
    }
    
  7. Swift switch statement with where clause:

    Description: The where clause in a switch statement allows additional conditions for matching cases.

    let age = 25
    
    switch age {
    case 0..<18:
        print("Child")
    case 18..<65 where age % 2 == 0:
        print("Adult with even age")
    case 18..<65 where age % 2 != 0:
        print("Adult with odd age")
    default:
        print("Senior")
    }
    
  8. Advanced usage of switch statement in Swift:

    Description: Advanced usage includes combining multiple patterns and conditions for complex matching.

    let value: Any = 42
    
    switch value {
    case let intValue as Int where intValue > 0:
        print("Positive integer")
    case let doubleValue as Double where doubleValue < 0:
        print("Negative double")
    case is String:
        print("It's a string")
    default:
        print("Unknown type")
    }