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 如何知道要使用哪个实现?


- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01