首页 > 解决方案 > 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 {

            }
        }
    }
}

在此处输入图像描述

标签: error-handlingcastingtype-conversionswift5

解决方案


事实证明我需要使用相等和 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)")

推荐阅读