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"
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With