14

I have the following code:

switch self.score
        {
        case 1:
            self.score = self.score - 2
        case -10...-10000: // ! Expected expression after unary operator
            println("lowest score")
            self.score = -10
        default:
            self.score = self.score - 1
        }

I have also tried case -1000...-10:. Both get the same error ! Expected expression after unary operator.

What I would really like to do is case <= -10:, but I can't figure out how to that without getting this error Unary operator cannot be separated from its operand.

What am I not understanding?

webmagnets
  • 2,266
  • 3
  • 33
  • 60

1 Answers1

19

In the context of a switch case, a ... b is a "closed interval" and the start must be less or equal to the end of the interval. Also a plus or minus sign must be separated from ... by a space (or the number enclosed in parentheses), so both

case -10000...(-10):
case -10000 ... -10:

work.

case <= -10: can be written in Swift using a "where clause":

case let x where x <= -10:

Starting with Swift 4 this can be written as a “one-sided range expression”:

case ...(-10):
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 2
    @webmagnets: In the "Where" section of the documentation: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html: *"A switch case can use a where clause to check for additional conditions ..."* – Martin R Jan 03 '15 at 15:30