How to use negative numbers in a range in Swift?

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 also tried case -1000...-10: Both get the same error ! Expected expression after unary operator ! Expected expression after unary operator .

I would like to do this case <= -10: but I cannot figure out how to do this without getting this error Unary operator cannot be separated from its operand .

What? I do not understand?

+8
source share
1 answer

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

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

Job.

case <= -10: can be written to Swift using "where":

 case let x where x <= -10: 

Starting with Swift 4, this can be written as a "one-way range expression":

 case ...(-10): 
+10
source

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


All Articles