On exhaustive switch statements

Just how smart is Swift really when it comes to exhaustive switch clauses?

Introduction

Disclaimer: this is only semi-serious.

From The Swift Programming Language (Swift 2 Edition):

Every switch statement must be exhaustive. That is, every possible value of the type being considered must be matched by one of the switch cases.

Well Swift let’s see if you really mean it:

exhaustive.swift
let number: UInt8 = 7

switch number {
case 0: print("0")
case 1: print("1")
case 2: print("2")
case 3: print("3")
case 4: print("4")
case 5: print("5")
case 6: print("6")
case 7: print("7")
case 8: print("8")
// ... truncated for clarity ...
// ... but you get the point ...
case 254: print("254")
case 255: print("255")
}
$ swift exhaustive.swift
exhaustive.swift:260:1: error: switch must be exhaustive, consider adding a default clause
}
^

I was lied to.

If you want to experiment on your own, here’s the program that writes the program:

let cases = (0...255).map { n in
    return "case \(n): print(\"\(n)\")"
}.joinWithSeparator("\n")

let source = "let number: UInt8 = 7\n\n" +
             "switch number {\n" +
             cases + "\n" +
             "}\n"

try! source.writeToFile("exhaustive.swift",
                        atomically: true,
                        encoding: NSUTF8StringEncoding)

Note: I expected to use UInt8.min...UInt8.max for the range. However that will not work, as explained by Ole Begemann in Ranges and Intervals in Swift.

By the way, I’m curious if anyone else immediately thought about trying this out after learning about switch in Swift. I can’t be the only one, can I?

Łukasz Adamczak's Picture

About Łukasz Adamczak

I'm a mobile & web developer based in Warsaw, Poland. On this blog I write down notes from my programming journeys.

Warsaw, Poland http://czak.pl

Comments