Error Handling with Enum Result Type

    Error Handling back then

    The example can be designed for a website.

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

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

    Test

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

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

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

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

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

    7007_result_type_error_handling

    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.