Error Handling with Enum Result Type

Introduction

Welcome to the last lesson of Chapter 7. You will learn how to combine two enums to throw and handle errors without using the Swift 3.1 error handling syntax.

Problem

Error Handling back then

HTTPS Request

The example can be designed for a website.

Design Error

Create a enum, HTTPError. It contains two error cases: nonFound404 and forbidden403.

  1. enum HTTPError {
  2. case notFound404
  3. case forbidden403
  4. }

Note: The Error protocol is not required

Design Result Type

Create a generic enum, ResultType. Like Optional, it contains two cases: Success(T) AND failure(HTTPError).

  1. enum ResultType<T> {
  2. case success(T)
  3. case failure(HTTPError)

Test

  1. let success = ResultType.success("Bob")
  2. let failure: ResultType<String> = ResultType.failure(.notFound404)
  3. }

Important: Remember to define T when you use the failure case.

Design Function and Return Error

Create a function called findSubDomain. You need to enter String. It will return ResultType<String>.

  1. func findSubDomain(subdomain: String) -> ResultType<String> {
  2. // Switch Statement
  3. switch subdomain {
  4. case "business":
  5. return ResultType.failure(.forbidden403)
  6. case "blog":
  7. return ResultType.failure(.notFound404)
  8. default:
  9. return ResultType.success("Found website")
  10. }
  11. }

Execute the function and create an instance, result, to store the returned value of ResultType<String>.

  1. let result = findSubDomain(subdomain: "business")

Handle Error

Once the function returns, you may use a classic switch statement to determine whether the instance is .failure or .success.

  1. switch result {
  2. case let .success(subDomainName):
  3. print(subDomainName)
  4. case let .failure(errorType):
  5. switch errorType {
  6. case .notFound404:
  7. print("Not Found: 404")
  8. case .forbidden403:
  9. print("Not Allowed: 403")
  10. }
  11. }

No need to get fancy with try, catch, and throw

Source Code

7007_result_type_error_handling

Conclusion

It’s up to you which method you prefer, the old or the new. The iOS platform itself uses the new syntax since it provides higher readability due to the explicit keywords such as try, catch, and throws. However, you still need to know how to send and handle errors using a ResultType enum because some developers still prefer the earlier method. You’ve got to know all.

In the following chapter, you will have one more lesson about The Swift error handling. There is one keyword you’ve got to know.

Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.