Stephen Martinez Stephen Martinez - 1 month ago 10
Swift Question

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

Answer

Is a simple solution, cast 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

Comments