Error Handling

Error handling allows you to determine the underlying cause of failure, and, if necessary, propagate the error to another part of your program.

When a function encounters an error condition, it throws an error. That function’s caller can then catch the error and respond appropriately.

do {
    try makeASandwich()
    eatASandwich()
} catch SandwichError.outOfCleanDishes {
    washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
    buyGroceries(ingredients)
}

Assertions and Preconditions

Assertions and preconditions are checks that happen at runtime. You use them to make sure an essential condition is satisfied before executing any further code.

If the condition evaluates to false, the current state of the program is invalid; code execution ends, and your app is terminated.

Assertions are checked only in debug builds, but preconditions are checked in both debug and production builds.

In production builds, the condition inside an assertion isn’t evaluated.

enum BackendError: Error {
  case urlError(reason: String)
  case objectSerialization(reason: String)
}

guard let responseData = data else {
    let error = BackendError.objectSerialization(reason: "No data in response")
    completionHandler(nil, error)
    return
}

results matching ""

    No results matching ""