swift - Swift dynamicType 返回什么?

标签 swift dynamic swift2 metaprogramming metaclass

考虑下面的例子:

enter image description here

class P {}
class C: P {}
let i: P = C()

let iDT = i.dynamicType
let CS = C.self

iDT == CS
iDT === CS

iDT.dynamicType == CS.dynamicType

iDT.dynamicType
CS.dynamicType

问题是:为什么iDT.dynamicType P.Type.Type? 我希望它是 C.Type.Type

最佳答案

这样会更简单:

class A {}
class B:A {}
let i: A = B()
i.dynamicType
i.dynamicType.dynamicType

所以我们可以推断出 i.dynamicTypei 真正的类型(多态),但是 i.dynamicType.dynamicType 是type i 被键入为。请注意,它不是 A;它是 A.Type,一种元类型。 dynamicType.dynamicType 的概念是一种边缘情况,因此这大概是一个实现细节。

在 REPL 中做这一切很有趣:

  1> class A {}
  2> class B:A {}
  3> let i : A = B()
i: B = {
  __lldb_expr_1.A = {}
}
  4> i.dynamicType
$R0: A.Type = __lldb_expr_3.B
  5> i.dynamicType.dynamicType
$R1: A.Type.Type = metatype for __lldb_expr_1.A

关于swift - Swift dynamicType 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38113888/

相关文章:

ios - 针对 iPhone 中的不同屏幕改变 UITextFields 的高度和间距

iOS:UICollectionViewCell 根据屏幕大小自动调整大小

ios - Swift - 单独的 View 有共享相同内存的 subview ?

swift - 在 Swift 2.2 中替换 _stdlib_getDemangledTypeName()

swift - 创建多个略有变化的 Sprite 节点?

ios - 如何从触摸点呈现 ViewController?

javascript - 将 ID 添加到按钮,但必须根据 radio 输入选择进行更改

objective-c - 动态库未在 Cocoa 应用程序中卸载

node.js - 如何使用 node express 为每个用户创建动态子域?

swift - 实现 KVO 投诉属性的协议(protocol)扩展