Sometimes there’s code so commonplace that we forget how strange it actually is. I mean, Swift is a strongly typed language right? Types types types! We say what things are, and the compiler enforces it for us. But then you see some piece of code like this:
func addOne(_ x: Int) -> Int {
fatalError("Haha! No Int for you!")
}
That’s legal Swift. I don’t think many would find that surprising. Of course that’s legal, right? But it is surprising. addOne
claims to be a function that accepts an Int and returns an Int. It does accept an Int, but…it doesn’t return an Int.
“Don’t be silly, Rob. It crashes. It can’t return an Int if it crashes.”
Well, yeah. But it promised to return an Int. It didn’t promise to “return an Int or crash,” did it? The whole point of strong types was that the compiler would enforce our promises, and the compiler doesn’t bat an eye at this code.
“The compiler can’t possibly know everything that might crash.”
I’m not ready to concede that, but even so, the compiler clearly can see that this function doesn’t return an Int. There’s no return intValue
anywhere. This should prick our ears a bit. Something is strange here. Is it just compiler magic, or is there something deeper?
Hint: There’s something deeper.