A type representing an error value that can be thrown.
- Xcode 8.0+
- Swift Standard Library
Any type that declares conformance to the
Error protocol can be used to represent an error in Swift’s error handling system. Because the
Error protocol has no requirements of its own, you can declare conformance on any custom type you create.
Using Enumerations as Errors
Swift’s enumerations are well suited to represent simple errors. Create an enumeration that conforms to the
Error protocol with a case for each possible error. If there are additional details about the error that could be helpful for recovery, use associated values to include that information.
The following example shows an
Int enumeration that captures two different kinds of errors that can occur when parsing an integer from a string: overflow, where the value represented by the string is too large for the integer data type, and invalid input, where nonnumeric characters are found within the input.
invalid case includes the invalid character as an associated value.
The next code sample shows a possible extension to the
Int type that parses the integer value of a
String instance, throwing an error when there is a problem during parsing.
When calling the new
Int initializer within a
do statement, you can use pattern matching to match specific cases of your custom error type and access their associated values, as in the example below.
Including More Data in Errors
Sometimes you may want different error states to include the same common data, such as the position in a file or some of your application’s state. When you do, use a structure to represent errors. The following example uses a structure to represent an error when parsing an XML document, including the line and column numbers where the error occurred:
Once again, use pattern matching to conditionally catch errors. Here’s how you can catch any
XMLParsing errors thrown by the