error-handling - iOS Swift5如何检查对象是否是在类型数组[Class.Type]中声明的类型?
问题描述
我正在尝试错误处理,并且对我可以用一系列类类型做什么很感兴趣。
有没有办法让我检查一个对象是否是在 [Class.Type] 数组中声明的类型?
"is" 运算符拒绝使用从数组中提取的类型。如何检查一个对象是否可以转换为该类型或者是该类型的一个实例?
class FooError: NSError { ... }
class BarError: NSError { ... }
protocol ErrorHandling {
var types: [NSError.Type] { get }
func handle(error: NSError)
}
class ErrorHandler: ErrorHandling {
var types = [FooError.self, BarError.self]
func handle(error: NSError) {
for errorType in types {
if error is errorType {
}
}
}
}
解决方案
事实证明我需要使用相等和 type(of:) 函数
public func handle(error: NSError) {
for errorType in types {
if type(of: error) == errorType {
print("Handling: \(error), \(errorType)")
return
}
}
print("Could not handle: \(error))")
}
let api = ErrorHandler()
api.handle(error: FooError())
api.handle(error: BarError())
api.handle(error: NSError(domain: "test", code: 0, userInfo: nil))
Handling: Error Domain=test Code=0 "(null)", FooError
Handling: Error Domain=test Code=0 "(null)", BarError
Could not handle: Error Domain=test Code=0 "(null)")
推荐阅读
- python - 轴上的 Numpy 乘法
- oracle - 在 Centos OS 上安装 oracle 时出现事务检查错误
- c - 文档类型元素 libxml
- android - 当 showAsAction="never" 时向菜单项添加图标
- python - TPOT:在 COLAB 中工作时,拟合后导出的最佳管道(.py 文件)在哪里
- javascript - VueFire 监视空数组属性
- java - 在 Spring 集成应用程序启动时意外 CryptoAPI 失败生成种子
- python - python中的方程和数学
- video - 使用 ffmpeg 生成单个 MPEG-Dash 片段
- oracle - 如何在 Oracle 12.1.0.2 中优化此查询?