comment 1

#32 Errorify String

Swift.Error

Swift introduces pattern of throwing errors, to propagate error conditions in a program. Errors are represented by types that conform to empty Error protocol, usually enum types.

If you want to propagate an error condition in your app, you can use your AppError enum for that:

The throws keyword says that a function can propagate an error, so it should be used with special care. All calls to the method have to be marked with try keyword and embedded in do{} catch{} block:

There is one dirty trick to get rid of do{} catch{} block. You can fore try! the method that throws:

❗️Remember: force try! causes your app to crash in the case your method actually propagates an error. In order to call the method seamlessly you can use try? to tell the compiler you’re not interested in the error.

In Swift a method can be marked with rethrows keyword. It means that it throws an error only if one of its arguments throws an error.

Named just Error

You may want to name your Error-conforming type simply Error. In order to do that, you have to point out that your Error conforms to protocol defined in standard Swift library:

Errorify String

Some time ago I was watching episode 11 of Swift Talk and I noticed that Florian and Chris are using String to throw an error.

I thought "Cool, I didn’t know you can do such things in Swift!". So I typed it in my code, and I was disappointed …


In order for the mechanism to work, I had to Errorify String 😉:

TL;DR;

1 Comment so far

  1. Shai Mishali

    Only problem with this is you lose the specificity for which the Error type was made for. But this is definitely comfortable for testing around and just a cool proof of how powerful are Swift Protocols

Leave a Reply


*