iOS Swift5, как я могу проверить, имеет ли объект тип, объявленный в массиве типов [Class.Type]? - PullRequest
0 голосов
/ 07 июля 2019

Я экспериментирую с обработкой ошибок и мне интересно, что я могу сделать с массивом типов классов.

Есть ли способ проверить, относится ли объект к типу, объявленному в массиве [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 {

            }
        }
    }
}

enter image description here

Ответы [ 2 ]

0 голосов
/ 07 июля 2019

Оказывается, мне нужно было использовать функцию равенства и типа (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)")
0 голосов
/ 07 июля 2019

Оператор Swift для этого равен is, см. Пример ниже

if object is Class.Type {
    // object is of type Class.Type
}
...