Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Error is subclass of NSError

Tags:

ios

swift

cocoa

I want a function which, for any given Error, will give me some description of it

protocol CustomError { }

func customDescription(_ error: Error) -> String {
    switch error {
    case let customError as CustomError:
        return "custom error"
    case ???:
        return "not subclass of NSError"
    case let nsError as NSError:
        return "subclass of NSError"
    }
}

Above is not the real code, and I don't want a String description, but a Dictionary, but this is not important in context of the question.

The problem is I don't know how to distinguish Errors which is subclass of NSError and which is not because any swift error could be bridged to NSError. Is it possible in swift?

like image 466
Maxim Kosov Avatar asked Jan 21 '26 11:01

Maxim Kosov


2 Answers

As you already noticed, any type conforming to Error can be bridged to NSError, therefore error is NSError is always true, and a cast error as NSError does always succeed.

What you can do is to check the dynamic type of the value with type(of:):

type(of: error) is NSError.Type

evaluates to true if error is an instance of NSError or a subclass.

like image 97
Martin R Avatar answered Jan 24 '26 18:01

Martin R


private protocol _NSError: Error { // private, so _NSError is equal to NSError
}

extension NSError: _NSError {

}

public func customDescription(_ error: Error) -> String {
    switch error {
    case let nsError as _NSError:
        print(nsError as! NSError)
        return "NSError"
    default:
        return "others"
    }
}
like image 40
linqingmo Avatar answered Jan 24 '26 16:01

linqingmo