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?
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.
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With