Swift callbacks can throw today

Nathan Herald
Nov 29, 2017 · 2 min read

Hey Chris,

Thank you for the link. Cocoa with Love is always a great resource.

However, it has been possible to throw from callbacks since Swift 2.

I’ve prepared a Gist to show an example:

Here is a gist that would work in Playgrounds as well.

I beleive the issue is that many people are not being clear with their intentions: if one wanted a callback to receive an argument that can throw, then that callback must receive a function. (Since only functions can throw.) Swift as a language, so far, has decided that the only place throws can be used is synchronous functions, so one must deal in those to provide an API that can return two types of things.

Most swift async libraries currently require a developer to supply callbacks which receive some other data types as arguments like an enum or a Result<T> type like the article you posted. But this is not necessary: functions are first class and are a completely reasonable value to provide to a callback function as an argument.

It is my opinion that many developers using swift are jumping too quickly to what they know from other languages and creating their own result objects now, instead of embracing what the language offers today. In the end it’s just code and it’s just personal style, but I try to fit into a language I use and I try to pay attention to it’s core features and what they are trying to teach me. The above gist would be my preferred style for any async operation that can fail.

Nathan Herald

Written by

I work on products and drink coffee.

More From Medium

Also tagged Error Handling

Also tagged Swift

Also tagged Programming

Also tagged Programming

ImportError: No module named 'XYZ'


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade