iOS One Sided Ranges

Michael Psoinos
Michael Psoinos
8,132 Points

How is this switch statement not exhaustive?

let value = -2

switch value {

case 1...: print("(value) is a positive number")

case ..<0: print("(value) is a negative number")

case 0: print("Zero!")


The compiler gives an error that this is not exhaustive. 1 to infinity, negative infinity to 0, and 0. What other value could there be?

Sohail Basha
Sohail Basha
2,236 Points

Hey Michael. It might have to do something with the minimum and maximum values of Int's.

There is no such thing as infinity or negative infinity. They do in fact have limits. Int.min is -9223372036854775807 whereas Int.max is 9223372036854775807. So what you have cannot be exhaustive.

Also, I noticed if value is set to anything more or less than its limits will give you an overflow error. But if it's being calculated, who knows.

1 Answer

Niki Molnar
Niki Molnar
21,770 Points

Hi Michael

As Sohail says in his comment, there is no such thing as infinite number in iOS but there could be an infinite loop, which is why Swift always needs a default statement.

It’s explained at 5’40 in the video:

“Because here we're using a range of values, and the switch statement can't infer that we've covered all our cases, so we'll say default: fatalError()”

Hope that helps


Michael Psoinos
Michael Psoinos
8,132 Points

If I understand correctly what you and Sohail are saying, "..<0" means Int.min to -1, and "1..." means 1 to Int.max, and anything beyond these ranges are possible values even though Int can't store them. I guess that makes sense. So when switching on Ints, you always need a default case.

I just tried switching on Double ranges of "0..." and "..<0" and still get the error message "Switch must be exhaustive". I guess you need a default case with any kind of number.

Thank you Sohail and Niki. Since Niki's post is the only one posted as an answer, I'll mark this one as answered.