在运行时,Swift 如何知道要使用哪个实现? [英] At runtime, how does Swift know which implementation to use?

查看:36
本文介绍了在运行时,Swift 如何知道要使用哪个实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
" "S2
"

如果这是一个继承层次结构,我希望 Swift 使用 v-table 来查找正确的实现.然而,array 中的具体类型可以是任何实现 A 的类型,以及任意数量的其他协议,所以 Swift 运行时如何知道对象的结构,如果它也在使用 v-tables 吗?

If this was an inheritance hierarchy, I would expect Swift to use a v-table to look up the correct implementation. However, the concrete types in array could be anything that implements A, along with any number of other protocols, so how would the Swift runtime know the structure of the object if it was also using v-tables?

推荐答案

Swift 运行时使用一个 Protocol Witness Table,它包含指向每个类型的协议方法实现的指针.

The Swift runtime uses a Protocol Witness Table which holds pointers to each type's implementations of the protocol methods.

Mike Ash 在他的文章 探索 Swift 内存布局,第二部分:

Mike Ash explains it best in his article Exploring Swift Memory Layout, Part II:

最后一个,在偏移量 32 处是底层类型和协议的协议见证表",其中包含指向协议方法的类型实现的指针.这就是编译器能够在运行时不知道底层类型的情况下对协议类型的值调用方法(例如 p())的方式.

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 视频 了解 Swift 性能 正如 Hamish 在评论中所建议的那样.

I would also watch the WWDC video Understanding Swift Performance as suggested in the comments by Hamish.

这篇关于在运行时,Swift 如何知道要使用哪个实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆