【发布时间】:2019-05-20 00:43:55
【问题描述】:
当涉及到多态性和动态类型时,我刚刚在 swift 的继承处理中遇到了一个奇怪的行为。下面的代码显示了我遇到的问题,基本上是:动态类型被正确识别(print("type(of: self) = \(classType)")打印),但是泛型函数testGeneric使用了错误的类型。
class Global {
static func testGeneric<T: TestSuperClass>(of type: T.Type) {
print("T.Type = \(T.self)")
}
}
class TestSuperClass {
func run() {
let classType = type(of: self)
print("type(of: self) = \(classType)")
Global.testGeneric(of: classType)
}
}
class TestClass: TestSuperClass {
}
class TestClass2: TestSuperClass {
override func run() {
let classType = type(of: self)
print("type(of: self) = \(classType)")
Global.testGeneric(of: classType)
}
}
let testClass = TestClass()
let testClass2 = TestClass2()
testClass.run()
testClass2.run()
打印输出是
type(of: self) = TestClass
T.Type = TestSuperClass
type(of: self) = TestClass2
T.Type = TestClass2
所以基本上在调用testClass.run() 时,type(of: self) 会产生TestClass,这是我所期望的。问题在于,随后立即调用的通用函数testGeneric 不知何故不适用于TestClass,而是使用TestSuperClass。
我个人的期望是
type(of: self) = TestClass
T.Type = TestClass
type(of: self) = TestClass2
T.Type = TestClass2
即,通用函数 testGeneric 在通过 testClass.run() 调用时使用类型 TestClass 而不是 TestSuperClass。
问题:
- 你对此有什么解释吗?
- 我怎样才能得到我想到的行为?
【问题讨论】:
标签: swift inheritance dynamic polymorphism dynamictype