Hi there, I'm Marcos!

Back

Creating a custom Error in swift

Sometimes you’ll want to create your own errors to be thrown once something wrong happens within your application. For this, Swift provides the Error protocol that you can use:

struct InvalidInputError: Error {
    message: String
}

The Error protocol doesn’t have any requirement on its own so you can define whatever information you need inside it.

I’ve used a struct above to create a custom error but Apple’s documentation states that for simple errors enum constructs are well suited as well:

enum ConversionError: Error {
  case unknownCharacter
    case emptySource
}

Here’s an example of how you can use this custom error:

func convertValue(value: String) {
    if value.isEmpty {
        throw ConversionError.emptySource
    }
    // ...
}