2016-10-16 89 views
4

我試圖創建一個Switch語句(Swift),它在case大於給定數字時返回一個String。我知道這可以用「if」或「else if」語句來完成,但我正在用Switch語句完成此操作。可以這樣做嗎?或者是一個Switch語句無法利用「大於」比較運算符?Swift:在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" 
} 
+0

你也可以寫'案件101 ... Int.max: ...' –

回答

5

是一個簡單的解決方案,將其綁定到這樣一個常數:

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" 
} 

這作品完全一樣,你需要