swift - 在运行时,Swift 如何知道要使用哪个实现?

标签 swift polymorphism method-dispatch

protocol A {
    func f()
}

struct S1 : A {
    func f() {
        print("S1")
    }
}

struct S2 : A {
    func f() {
        print("S2")
    }
}

let array: [A] = [S1(), S2()]

for s: A in array {
    s.f()
}

// "S1\n" "S2\n"

如果这是一个继承层次结构,我希望 Swift 使用 v 表来查找正确的实现。但是,array 中的具体类型可以是任何实现 A 的对象,以及任意数量的其他协议(protocol),因此如果 Swift 运行时如何知道对象的结构也在使用 v 表?

最佳答案

Swift 运行时使用 Protocol Witness Table,其中包含指向每种类型的协议(protocol)方法实现的指针。

Mike Ash 在他的文章 Exploring Swift Memory Layout, Part II 中对其进行了最好的解释:

The last one, at offset 32 is a "protocol witness table" for the underlying type and the protocol, which contains pointers to the type's implementations of the protocol methods. This is how the compiler is able to invoke methods, such as p(), on a value of protocol type without knowing the underlying type at runtime.

我还会看 WWDC 视频 Understanding Swift Performance正如 Hamish 在评论中所建议的那样。

关于swift - 在运行时,Swift 如何知道要使用哪个实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38332616/

相关文章:

swift - 将 cookie 传递给 WKWebView/SFSafariViewController?

swift - CellForRow 被延迟调用

ios - 使用swift和Mapkit,显示用户当前位置到特定位置之间的路线

php - 多重继承和多态有什么区别?

Ruby:如何通过对象引用调用函数?

带有空参数的 Java 方法分派(dispatch)

ios - 通过包含 View Controller 传递数据的好方法是什么

类外的C++虚函数实现

entity-framework - Entity Framework 不查询派生类 - DbOfTypeExpression 中的错误

Java动态绑定(bind)