【问题标题】:Apple's own Swift documentation seems wrong about dynamicType vs compile-time typeApple 自己的 Swift 文档关于 dynamicType 与编译时类型似乎是错误的
【发布时间】:2016-04-03 19:48:14
【问题描述】:

参考:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html

我们有:

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


【解决方案1】:

这是一个错字——向你致敬。该部分是关于 Metatype 类型的,他们在整个部分都使用 type_name.self,除了那一行。

除了 dynamicType 像宣传的那样工作——这里没有错。

【讨论】:

    【解决方案2】:

    我怀疑

    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],

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多