Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS One Sided Ranges

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?

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
25,698 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

Niki

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.