TIL: Typed do in Swift
TL;DR: Swift has do throws(MyError). It's helpful.
This is one of those "I can't believe I had missed that" things.
I've been pretty enthusiastic about adopting typed throws in Swift. If you need to process certain kinds of errors, it just makes sense to me. However, it was always a bit painful. You have this:
do {
// throwing code here
} catch {
// error is precisely typed here, assuming
// the block above throws just one type
}
… and all is fine and good, except that the "throwing code" doesn't need to
grow particularly complex before Swift decides to widen the type to any Error
and your catch block starts producing compilation errors.
When I ran into this, I'd use catch let error as MyError. Fine. Except it
isn't, because now your error-handling code is incomplete: you have to add
an unreachable catch-all block, and you're unhappy with the language and
your life choices.
I did page through the enhancement proposal when it passed through Swift Evolution, but I just never noticed that it doesn't end there. What you do in this situation is this:
do throws(MyError) {
// throwing code here
} catch {
// now the compiler doesn't get confused and
// all is well-typed unicorns and sunshine
}
Now you know too.