Swift: Using the Comparison Operator in a Switch Statement

I am trying to create a Switch (Swift) statement that returns a string when the case is greater than the given number. I know that this can be done using an "if" or "else if" statement, but I want to do this using a Switch statement. Is it possible to do this, or is it a Switch statement that a “comparative” operator cannot use?

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"
}
+4
source share
1 answer

This is a simple solution, bind it to a constant as follows:

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

It works exactly as you need.

+6
source

Source: https://habr.com/ru/post/1657892/


All Articles