Juri Pakaste: TIL: Typed do in... Note

Juri Pakaste: TIL: Typed do in Swift

The author discovered a valuable feature in Swift's typed throws that simplifies error handling. Initially, they found typed throws very useful for specific error types but encountered a problem where complex code blocks would cause Swift to widen the error type to 'any Error'. This meant their 'catch' block would no longer precisely type the error, leading to compilation issues. Their workaround involved using 'catch let error as MyError', but this necessitated an unreachable catch-all block, making the error-handling incomplete and frustrating. The critical discovery was the 'do throws(MyError)' syntax. By explicitly declaring the expected error type in the 'do' block, Swift's compiler maintains the precise error typing. This elegant solution prevents the compiler from getting confused, ensuring that the 'catch' block correctly handles the specified error type. This feature improves the clarity and completeness of error handling when working with typed throws in Swift. The author's oversight of this detail in the original enhancement proposal was a significant miss. Now, all is well-typed unicorns and sunshine.