Swift 案例陈述

Swift case statement

我正在尝试 Swift 3.0 中的 switch 语句 使用我的代码,无论我的变量是什么,我都会得到 A。 为什么我只得到 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")
}

开关是从上到下求值的,所以由于第一个测试满足(grade < 100),程序总是return A。你可以简单地颠倒案例的顺序。通常,您希望 switch 语句从最严格到最不严格。

switch 语句考虑一个值并将其与几种可能的匹配模式进行比较。然后它根据成功匹配的 first 模式执行适当的代码块。

在你的具体情况下尝试使用:

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.

此致