Search code examples
iosswiftswitch-statementstatements

Swift case statement


I'm trying switch statements in Swift 3.0 With my code, I get A, no matter what my variable is. Why am I only getting A?

var grade = 45

switch grade {

    case (grade ..< 100):
        print("A")
    case (grade ..< 90):
        print("B")
    case (grade ..< 80):
        print("C")
    case (grade ..< 70):
        print("D")

    default:
        print("F. You failed")
}

Solution

  • A switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully.

    In your specific case try to use:

    var grade = 45
    
    switch grade {
    
    case 90 ..< 100: //Numbers 90-99  Use 90...100 to 90-100
        print("A")
    case (80 ..< 90): //80 - 89
        print("B")
    case (70 ..< 80): // 70 - 79
        print("C")
    case (0 ..< 70): // 0 - 69
        print("D")
    
    default:
        print("F. You failed")//Any number less than 0 or greater than 99 
    
    }
    

    check this

    In contrast with switch statements in C and Objective-C, switch statements in Swift do not fall through the bottom of each case and into the next one by default. Instead, the entire switch statement finishes its execution as soon as the first matching switch case is completed, without requiring an explicit break statement. This makes the switch statement safer and easier to use than the one in C and avoids executing more than one switch case by mistake.

    Regards