Switch on Int with exhaustive cases still needs default?

If the cases of my switch on an Int cover every number from Int.min to Int.max, why does it still make me put a default?

For example:

let number = 5

switch number {
case Int.min ... 0:
    print("Too small")
case 1...100:
case 101 ... Int.max:
    print("Too big")

Even though there isn’t a value number could be that is not covered by these three cases, I still get “Switch must be exhaustive” (in a Swift Playground).

I know I could change the final case to default: or case _: to satisfy the compiler, but at the cost of expressiveness. Why doesn’t the compiler recognize that this switch is exhaustive?

AFAIK, currently, there isn't exhaustive checking in place for types beyond enums & tuples (don't quote me on that).


That makes sense and is reasonable.

See https://bugs.swift.org/browse/SR-766

Unfortunately, integer operations like '...' and '<' are just plain functions to Swift, so it'd be difficult to do this kind of analysis. Even with special case understanding of integer intervals, I think there are still cases in the full generality of pattern matching for which exhaustiveness matching would be undecidable. We may eventually be able to handle some cases, but there will always be special cases involved in doing so.

and Bool :)


Huh. I’d never looked up the Bool definition. I’d always assumed it was an enum. Apparently it is a struct.

Bool used to be an enum in Swift’s early days. It was changed to a struct in late 2013.

1 Like
Terms of Service

Privacy Policy

Cookie Policy