检查对象是否继承了swift中的泛型类或任意类

时间:2017-05-30 15:15:29

标签: ios swift inheritance

我有一组可变的类 - 或更好的类类型 - 并希望检查一个随机对象 - 直接或间接 - 继承任何这些类。

我使用===编写了一个小型Playground Test进行直接继承检查,并使用isas?进行间接检查:

import Foundation

protocol Product {init()}

class LowGradeProduct: Product {required init() {}}
class HighGradeProduct: Product {required init() {}}

class A: LowGradeProduct {}
class B: HighGradeProduct {}
class ExtraFancyB: B {}
class C: HighGradeProduct {}
class RandomClass {}

class SnobjectChecker {
    var allowedClass: [HighGradeProduct.Type] = []

    func addCls( cls: HighGradeProduct.Type ) {
        allowedClass.append(cls)
    }

    func checkCls( obj: AnyObject ) -> Bool {
        for allowedCls in allowedClass {

            /* 1. check object class equality, works */
            if type(of: obj) as AnyClass === allowedCls as AnyClass {
                return true
            }

            /* 2. check object class heritance via upcast: not working */
            if let _ = obj as? allowedCls {
                return true
            }


            /* 3. check object class heritance via is: not working  */
            if obj is allowedCls {
                return true
            }
        }
        return false
    }

}

let fac = SnobjectChecker.init()

fac.addCls(cls: B.self)

for cls in [A.self, B.self, C.self, ExtraFancyB.self] as! [Product.Type] {
    print("object of \(cls) is allowed: \(fac.checkCls(obj: cls.init() as AnyObject))")
}
print("object of \(RandomClass.self) is allowed: \(fac.checkCls(obj: RandomClass.init() as AnyObject))")

对类同等性的检查有效,但它错过了ExtraFancyB等间接继承。

is和upcast as?都不起作用,似乎它们都只允许静态类型,因为编译器抱怨缺少类型allowedCls

还有另一种方法可以检查一个对象是否继承了一组随机类,以便使用swift 2.3 / 3 +实现这一目标,并且如果可能的话,没有像classname比较这样的黑客攻击?

0 个答案:

没有答案