Add ability to specify the error type on throws


(Mark Robinson) #1

Hello,

Consider the scenario of the vending machine example in the Swift Book:

We have a function that throws errors from a single given ErrorType

   1. func vend(itemNamed name: String) throws {
   2. guard let item = inventory[name] else {
   3. throw VendingMachineError.InvalidSelection
   4. }
   5.
   6. guard item.count > 0 else {
   7. throw VendingMachineError.OutOfStock
   8. }
   9.
   10. guard item.price <= coinsDeposited else {
   11. throw VendingMachineError.InsufficientFunds(coinsNeeded: item.price
   - coinsDeposited)
   12. }

In this scenario - when we have a function that throws a single type of
error - I believe it would be useful to be able to *optionally* specify the
type of error thrown from the vend function, so that the code would look
like this:

   1. func vend(itemNamed name: String) throws VendingMachineError {
   2. guard let item = inventory[name] else {
   3. throw .InvalidSelection
   4. }
   5.
   6. guard item.count > 0 else {
   7. throw .OutOfStock
   8. }
   9.
   10. guard item.price <= coinsDeposited else {
   11. throw .InsufficientFunds(coinsNeeded: item.price - coinsDeposited)
   12. }

The purpose is to just let the compiler know that all errors thrown from
this function will be of type VendingMachineError so there's no longer any
need to constantly prefix the enumeration cases with the enumeration type.

This makes the code much cleaner to read and stops repetition of
VendingMachineError.
In the scenario where there's multiple types of errors thrown from a
function, using throws as we do now without a type would suffice, as in
this case it makes sense that the programmer has to tell the compiler what
type the Error is via prefixing the enumeration case with the enumeration
type.

Cheers,
Mark


Why doesn't Swift have explicit throwables like Java