Swift Throws – I Get It

It took me a little while for me to really appreciate the design of throws. At first, it was sheer disbelief that the Swift team created exceptions. Then it was mild irritation that a Result<T, E> type wasn't used.

Now, I really like it.

I see a lot of discussion about it (and some with comments on my blog) and different proposals being made. One of the things I keep seeing being missed though, is that throws forces you to be explicit about handling, ignoring, or bubbling the error back up.

The thing that really won me over was remembering how many times I had to link to this guide: ObjC Error Handling. For me, I've been used to it for so long that it's easy to forget just how much convention there is there. I've also seen some pretty amusing code that is attempting to use NSError but it being so wrong.

It is a good thing that Swift has both codified and simplified the error handling conventions of Cocoa.

Also, there is no more ambiguity on how to handle this case:

- (int)ohCrapAScalar:(NSError **error) {
    // So... what magic value do I use this time?

With Swift, it's a non-issue (unless you're bridging with ObjC – rdar://21360155):

func scalarNoProblem() throws -> Int {

The other complaint I see is around async… well, I honestly thing that is a point-in-time problem. I think Swift will get something like await, and it seems it would be natural to have this:

try {
    await try someAsyncThrowingCode()   
catch {

Of course, that doesn't cover all async cases, but you get the idea.

Swift Throws – I Get It