【发布时间】:2016-04-03 19:48:14
【问题描述】:
参考:
我们有:
class SomeBaseClass {
class func printClassName() {
print("SomeBaseClass")
}
}
class SomeSubClass: SomeBaseClass {
override class func printClassName() {
print("SomeSubClass")
}
}
let someInstance: SomeBaseClass = SomeSubClass()
// The compile-time type of someInstance is SomeBaseClass,
// and the runtime type of someInstance is SomeBaseClass
someInstance.dynamicType.printClassName()
// prints "SomeSubClass"
使用恒等运算符(=== 和 !==)测试实例的运行时类型是否与其编译时类型相同。
if someInstance.dynamicType === someInstance.self {
print("The dynamic type of someInstance is SomeBaseCass")
}
else {
print("The dynamic type of someInstance isn't SomeBaseClass")
}
但someInstance.self 似乎指的是对象,而不是文档所声称的对象的编译时类型。事实上,在 Xcode 7.2 中,即使我们将 someInstance 初始化为 SomeBaseClass,测试也不会评估为真。
这并不能让人相信文档有错字 (SomeBaseCass)。
我能找到使“真”子句触发的唯一方法是突变:
if someInstance.dynamicType == SomeBaseClass.self { ... }
这很有趣,但错过了有缺陷的 Apple 文档试图展示的完全动态的运行时类型检查功能。
谁错了,如何解决?
【问题讨论】:
-
您可以file bugs 反对文档(它不仅适用于软件)...他们在纠正报告的错误方面做得很好。
-
错误归档为 #24026098。
标签: swift dynamic types swift2 xcode7