Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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 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?

like image 925
webmagnets Avatar asked Jan 03 '15 15:01

webmagnets


People also ask

Can range take negative?

No. Because the range formula subtracts the lowest number from the highest number, the range is always zero or a positive number.

How do you find the range with negative numbers?

The range of any data set is calculated by subtracting the lowest value from the highest value.

Can uint8_t be negative?

A uint8 data type contains all whole numbers from 0 to 255. As with all unsigned numbers, the values must be non-negative.

Can you use negative numbers in for loop?

As the name suggests, the positiveornegativenumber variable can contain either a positive or negative number. As a result, if said variable is positive, the for loop works. If it is negative, the loop exits immediately because i is already larger than negativeorpositivenumber.


1 Answers

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):
like image 57
Martin R Avatar answered Sep 29 '22 23:09

Martin R