At runtime, how does Swift know which implementation to use?(在运行时,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 如何知道要使用哪个实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在运行时,Swift 如何知道要使用哪个实现?
基础教程推荐
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
