Sharing passion in Swift

#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.

1

2

3

4

5

6

7

8

9

enumAppError: Error{

casetype1

casetype2

//..

casetypeN

}

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

1

2

3

4

5

6

7

8

funcbar()throws{

ifshouldThrowError(){

throwAppError.type1

}

}

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:

1

2

3

4

5

6

7

8

do{

trybar()

}catch{

print("\(error)")

}

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

1

2

3

4

try!bar()

❗️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.

1

2

3

4

try?bar()

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.

1

2

3

4

5

6

funcbar(callback:()throws->Void)rethrows{

trycallback()

}

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:

2 Comments

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