Ios 如何检查Error是否为NSError的子类
我想要一个函数,对于任何给定的Ios 如何检查Error是否为NSError的子类,ios,swift,cocoa,Ios,Swift,Cocoa,我想要一个函数,对于任何给定的错误,它都会给我一些描述 protocol CustomError { } func customDescription(_ error: Error) -> String { switch error { case let customError as CustomError: return "custom error" case ???: return "not subclass of NSErro
错误
,它都会给我一些描述
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"
}
}
上面不是真正的代码,我不想要字符串
描述,而是字典
,但这在问题的上下文中并不重要
问题是我不知道如何区分
Error
s,它是NSError
的子类,这不是因为任何快速错误都可以桥接到NSError
。在swift中可能吗?正如您已经注意到的,任何符合错误的类型都可以桥接
到NSError
,因此error is NSError
始终为真,并且强制转换
错误,因为NSError
总是成功
您可以使用type(of:)
检查值的动态类型:
如果error
是NSError
的实例或子类,则计算结果为true
。类似type(of:error)的内容就是NSError。type
可能会起作用。这与中的问题类似。我不确定为什么需要将NSError
案例与error
案例分开(它们是专门为互操作而设计的)–你想要得到的字典是什么?(这听起来对问题的上下文很重要)。可能有一个更好的解决方案,而不是试图用强制转换来区分这两种情况。
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"
}
}
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"
}
}