[swift-users] Every non-trivial Swift function should throw?

danielt1263 at gmail.com danielt1263 at gmail.com
Sat Mar 5 12:31:41 CST 2016


I think this write up makes two assumptions.

1) That a nil return from a function is a failure.
2) That there is more than one reason for it to fail.

If both of those assumptions hold then sure, the function should throw. You won't get an argument from me, but if not, I'm not so sure.

Take the canonical find function as an example. Returning nil does not represent an error, and if nil is returned, there is only one reason to do so. I see no reason why hat sort of function should throw. I'll go even further and say that if such a function did throw, it would confuse users. They would be left wondering what the possible reasons (not the plural) for throwing are...

Sent from my iPad

> On Mar 5, 2016, at 1:00 PM, swift-users-request at swift.org wrote:
> 
> "so pretty much every non-trivial #swift function should throw, right?
> cheap & gives caller choice to catch, rethrow, try? or try!  (4 in 1)"
> -- https://twitter.com/johnspurlock/status/704478619779866625
> 
> One of the annoying things about checked exceptions in other languages is
> that they somewhat dictate client behavior wrt error handling and flow.
> Also expensive (for some value of expensive) when they occur, so not a good
> choice for standard-case control flow.
> 
> Given that Swift provides multiple language-standard ways for clients to
> deal with a function marked as 'throws', it seems like almost all
> non-trivial shared functions should provide the additional information of
> the error in that standard form, instead of hiding it behind an optional
> return type or a bespoke error callback argument.
> 
> i.e. always:  func parse(str: String) throws -> Foo
> instead of: func parse(str: String) -> Foo?    // loss of information: why
> did it fail?


More information about the swift-users mailing list