0
0
Swiftprogramming~5 mins

Error protocol conformance in Swift

Choose your learning style9 modes available
Introduction

We use the Error protocol to create custom error types. This helps us handle mistakes in our programs clearly and safely.

When you want to define your own error messages for specific problems.
When you need to catch and respond to different errors in different ways.
When you want to make your code easier to understand by naming errors.
When you want to use Swift's error handling features like try, catch, and throw.
Syntax
Swift
enum MyError: Error {
    case somethingWentWrong
    case invalidInput(reason: String)
}

You usually create an enum that follows the Error protocol.

Each case represents a different kind of error you want to handle.

Examples
This enum defines three network-related errors.
Swift
enum NetworkError: Error {
    case badURL
    case timeout
    case unknown
}
You can also use structs or classes to conform to Error, not just enums.
Swift
struct FileError: Error {
    let message: String
}
This enum uses associated values to give more details about the error.
Swift
enum ValidationError: Error {
    case emptyField(fieldName: String)
    case invalidEmail
}
Sample Program

This program defines a LoginError enum that conforms to Error. The login function throws errors if the user or password is wrong. We use do-try-catch to handle these errors and print messages.

Swift
enum LoginError: Error {
    case userNotFound
    case wrongPassword
}

func login(user: String, password: String) throws -> String {
    if user != "admin" {
        throw LoginError.userNotFound
    }
    if password != "1234" {
        throw LoginError.wrongPassword
    }
    return "Welcome, \(user)!"
}

// Using the function with error handling

do {
    let message = try login(user: "admin", password: "1234")
    print(message)
} catch LoginError.userNotFound {
    print("Error: User not found.")
} catch LoginError.wrongPassword {
    print("Error: Wrong password.")
} catch {
    print("Unknown error.")
}
OutputSuccess
Important Notes

Only types that conform to the Error protocol can be thrown as errors.

Using enums for errors is common because they clearly list all possible errors.

Remember to handle errors with do-try-catch to avoid crashes.

Summary

The Error protocol lets you create your own error types.

Enums are a simple way to list different errors.

Use throw and catch to manage errors safely in your code.