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

查看:99
本文介绍了在运行时,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\n" "S2\n"

如果这是一个继承层次结构,我希望Swift可以使用v表查找正确的实现.但是,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运行时使用协议见证表,该表包含指向每种类型的协议方法实现的指针.

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天全站免登陆