Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Using a comparative operator in a Switch Statement

I'm trying to create a Switch statement (Swift) that returns a String when a case is greater than a given number. I know this can be done with an "if" or "else if" statement, but I'm looking to accomplish this with a Switch statement. Can this be done or is a Switch statement unable to utilize the "greater than" comparative operator?

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"
}
like image 949
Stephen Martinez Avatar asked Dec 19 '22 12:12

Stephen Martinez


1 Answers

Is a simple solution, bind it to a constant like this:

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

That works exactly as you need

like image 55
Mago Nicolas Palacios Avatar answered Jan 11 '23 22:01

Mago Nicolas Palacios