Itachi
Itachi

Reputation: 6070

Unbox Error for override property in Swift?

import Foundation

enum OperationError: Error {
    case ioError(_ message: String)

    var localizedDescription: String {
        switch self {
        case .ioError(let message):
            return message
        }
    }
}

func test1() throws {
    throw OperationError.ioError("io error")
}

do {
    try test1()
} catch {
    print("\(error) type: \(type(of: error))")
    print("\(error.localizedDescription)")
    print("\((error as? OperationError)?.localizedDescription ?? "")")
}

Output:

ioError("io error") type: OperationError
The operation couldn’t be completed. (SwiftErrorDemo.OperationError error 0.)
io error

It seems the custom error couldn't be invoked to the correct property, I know the localizedDescription property is from Foundation framework, but for real type of the error is OperationError, why does the override localizedDescription get called?

Upvotes: -1

Views: 54

Answers (1)

matt
matt

Reputation: 534885

If you want to supply your own localizedDescription, adopt LocalizedError.

enum OperationError: LocalizedError {
    case ioError(_ message: String)

    var errorDescription: String? {
        switch self {
        case .ioError(let message): message
        }
    }
}

Your test code stays the same:

func test1() throws {
    throw OperationError.ioError("io error")
}

do {
    try test1()
} catch {
    print("\(error) type: \(type(of: error))")
    print("\(error.localizedDescription)")
    print("\((error as? OperationError)?.localizedDescription ?? "")")
}

Output from your test code:

ioError("io error") type: OperationError
io error
io error

Upvotes: 2

Related Questions