How to create custom errors in Swift

Create an enum of type error and list the cases.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 09/12/2023 at 11:40
Last Updated on 09/12/2023 at 11:58
<p>Two flowers that represent Swift and XCode side by side. Beneath them sits the text "Custom Errors."</p>

Create an enum of type error and list the cases.

Subscribe

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
View RepositoryCheck out our SwiftData Quick Start Guide

Step One: Create the Errors

<p>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.</p>

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

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

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.

Learn more about Results

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe