Skip to content

Handle Error Gracefully In Swift

devedbox edited this page Nov 18, 2018 · 2 revisions

Error In Swift

Error handling is common is our daily coding works, an error normally indicates the unexpected conditions occurred during the process of program, but how to handle error info gracefully is a real work to care for.

Back in ObjC, we using NSError ** type to record our error info, we barely use it because it's really hard to use and mostly we don't have the needs.

Now in Swift, we use the protocol Error in the standard library and throws to handle our errors. The Error protocol is not like NSError ** in ObjC. It's more like NSException * in ObjC but it can do more than NSException *. With Error in Swift, we can make our codes more flexible and scalable.

Use It

You can read the Swift Language Guide to learn how to use error handling in Swift.

Define Your Function

A function accepts one or more parameters and return an output, which is straightforward. Before we define our function, we must be clear about what the function actually does and how it act. As an example in Commander,

Clone this wiki locally