Apple 自己的 Swift 文档关于 dynamicType 与编译时类型似乎是错误的
Apple's own Swift documentation seems wrong about dynamicType vs compile-time type
引用:
我们有:
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"
Use the identity operators (=== and !==) to test whether an instance’s runtime type is the same as its compile-time type.
if someInstance.dynamicType === someInstance.self {
print("The dynamic type of someInstance is SomeBaseCass")
}
else {
print("The dynamic type of someInstance isn't SomeBaseClass")
}
正如文档。事实上,在 Xcode 7.2 中,即使我们将 someInstance
初始化为 SomeBaseClass
.,测试也不会评估为真
文档有错字 (SomeBaseCass),这并不能激发人们的信心。
我能找到使 "true" 子句生效的唯一方法是突变:
if someInstance.dynamicType == SomeBaseClass.self { ... }
这很有趣,但错过了有缺陷的 Apple 文档试图展示的完全动态 运行 时间类型检查功能。
谁的错,如何解决?
这是一个打字错误 - 感谢您。该部分是关于 Metatype 类型的,他们在整个部分中使用 type_name.self 除了那一行。
除此之外,dynamicType 的工作方式与宣传的一样——这里没有任何问题。
我有疑问
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"
并且 someInstance 的运行时类型应该是 [SomeSubClass],
引用:
我们有:
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"
Use the identity operators (=== and !==) to test whether an instance’s runtime type is the same as its compile-time type.
if someInstance.dynamicType === someInstance.self {
print("The dynamic type of someInstance is SomeBaseCass")
}
else {
print("The dynamic type of someInstance isn't SomeBaseClass")
}
正如文档。事实上,在 Xcode 7.2 中,即使我们将 someInstance
初始化为 SomeBaseClass
.,测试也不会评估为真
文档有错字 (SomeBaseCass),这并不能激发人们的信心。
我能找到使 "true" 子句生效的唯一方法是突变:
if someInstance.dynamicType == SomeBaseClass.self { ... }
这很有趣,但错过了有缺陷的 Apple 文档试图展示的完全动态 运行 时间类型检查功能。
谁的错,如何解决?
这是一个打字错误 - 感谢您。该部分是关于 Metatype 类型的,他们在整个部分中使用 type_name.self 除了那一行。
除此之外,dynamicType 的工作方式与宣传的一样——这里没有任何问题。
我有疑问
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"
并且 someInstance 的运行时类型应该是 [SomeSubClass],