How to create custom errors in Swift

Oscar de la Hera Gomez
Two flowers that represent Swift and XCode side by side. Beneath them sits the text "Custom Errors."

Create an enum of type error and list the cases.

The following example can be found along with a simple app for demonstrating SwiftData through the tutorial/swift-data-basics branch on our Open Source Swift Starter Project.

git clone git@github.com:delasign/swift-starter-project.git

Step One: Create the Errors

A screenshot of Xcode showing a "SwiftDataError.swift" file. Within the file we have declared a SwiftDataError enum that has two cases: object already exists and object doesn't exist.

Create a new swift file and within it, create an Enum, of type Error that includes all the errors that you wish to track.

We recommend that you do this within a folder called "errors" under a "models" folder.

Step Two: Use the Errors

A screenshot of Xcode highlighting how we have applied the errors as enums within results to a Swift tasks.

In functions that produce errors, apply the error created in Step One as if you were using any other enum.

These errors can be particularly helpful as failed results within tasks.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details