为什么跟随is
检查错误?
class Person : BaseClass { ... }
class Parent : Person { ... }
.
.
let parent = Parent()
print("parent is BaseClass: \(parent.self is BaseClass)")
// this prints 'parent is BaseClass: false'
如何检查子类的基类或超类?特别是如果我不知道对象的子类有多深。
更新: 我的错误以下是真的
print("parent is BaseClass: \(parent.self is BaseClass)")
// this prints 'parent is BaseClass: true'
但这个不是
class GenericClass<T: BaseClass> { }
.
let myGeneric = GenericClass<Parent>()
print("myGeneric is GenericClass<BaseClass>: \(myGeneric.self is GenericClass<BaseClass>)")
// this prints 'myGeneric is GenericClass<BaseClass>: false'
在Playground我收到以下警告:
Playground.playground:从'GenericClass'转换为 不相关的类型'GenericClass'总是失败
那么如何检查基类的泛型关系呢?
答案 0 :(得分:1)
您必须将包含的类型公开为typealias。这是解决方案。
protocol BaseClass { }
class Person : BaseClass { }
class Parent : Person { }
class GenericClass<T: BaseClass> {
typealias Contained = T
}
let myGeneric = GenericClass<Parent>()
print("myGeneric is GenericClass<BaseClass>: \(type(of: myGeneric).Contained() is BaseClass)")