Swift:在Switch语句中使用比较运算符

时间:2016-10-16 01:09:42

标签: swift switch-statement

我试图创建一个Switch语句(Swift),当case大于给定数字时返回一个String。我知道这可以用" if"或者"否则如果"声明,但我想用Switch语句来完成这个。可以这样做,还是Switch语句无法使用"大于"比较运算符?

var score = 101
var letterGrade = ""

switch score{
    case >100:
    letterGrade = "A+ With Extra Credit"
case 90...100:
    letterGrade = "A"
case 80...89:
    letterGrade = "B"
case 70...79:
    letterGrade = "C"
case 60...69:
    letterGrade = "D"
default:
    letterGrade = "Incomplete"
}

1 个答案:

答案 0 :(得分:7)

是一个简单的解决方案,将它绑定到这样的常量:

    var score = 101
var letterGrade = ""

switch score{
case let x where x > 100:
    letterGrade = "A+ With Extra Credit"
case 90...100:
    letterGrade = "A"
case 80...89:
    letterGrade = "B"
case 70...79:
    letterGrade = "C"
case 60...69:
    letterGrade = "D"
default:
    letterGrade = "Incomplete"
}

完全符合您的要求