Which dispatch method would be used in Swift?

In this example:

protocol MyProtocol {

func testFuncA()

}

extension MyProtocol {

func testFuncA() {

print("MyProtocol‘s testFuncA")

}

}

class MyClass : MyProtocol {}

let object: MyClass = MyClass()

object.testFuncA()

static dispatch is used. The concrete type of object is known at compile time; it‘s MyClass. Swift can then see that it conforms to MyProtocol without providing its own implementation of testFuncA(), so it can dispatch straight to the extension method.

So to answer your individual questions:

MyClassMyClassNo – a Swift class v-table only holds methods defined in the body of the class declaration. That is to say:

protocol MyProtocol {

func testFuncA()

}

extension MyProtocol {

// No entry in MyClass‘ Swift v-table.

// (but an entry in MyClass‘ protocol witness table for conformance to MyProtocol)

func testFuncA() {

print("MyProtocol‘s testFuncA")

}

}

class MyClass : MyProtocol {

// An entry in MyClass‘ Swift v-table.

func foo() {}

}

extension MyClass {

// No entry in MyClass‘ Swift v-table (this is why you can‘t override

// extension methods without using Obj-C message dispatch).

func bar() {}

}

There are no existential containers in the code:

let object: MyClass = MyClass()

object.testFuncA()

Existential containers are used for protocol-typed instances, such as your first example:

let object: MyProtocol = MyClass()

object.testFuncA()

The MyClass instance is boxed in an existential container with a protocol witness table that maps calls to testFuncA() to the extension method (now we‘re dealing with dynamic dispatch).

A nice way to see all of the above in action is by taking a look at the SIL generated by the compiler; which is a fairly high-level intermediate representation of the generated code (but low-level enough to see what kind of dispatch mechanisms are in play).

You can do so by running the following (note it‘s best to first remove print statements from your program, as they inflate the size of the SIL generated considerably):

swiftc -emit-sil main.swift | xcrun swift-demangle > main.silgen

Let‘s take a look at the SIL for the first example in this answer. Here‘s the main function, which is the entry-point of the program:

// main

sil @main : [email protected](c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 {

bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>):

alloc_global @main.object : main.MyClass       // id: %2

%3 = global_addr @main.object : main.MyClass : $*MyClass // users: %9, %7

// function_ref MyClass.__allocating_init()

%4 = function_ref @main.MyClass.__allocating_init() -> main.MyClass : [email protected](method) (@thick MyClass.Type) -> @owned MyClass // user: %6

%5 = metatype [email protected] MyClass.Type              // user: %6

%6 = apply %4(%5) : [email protected](method) (@thick MyClass.Type) -> @owned MyClass // user: %7

store %6 to %3 : $*MyClass                      // id: %7

// Get a reference to the extension method and call it (static dispatch).

// function_ref MyProtocol.testFuncA()

%8 = function_ref @(extension in main):main.MyProtocol.testFuncA() -> () : [email protected](method) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> () // user: %12

%9 = load %3 : $*MyClass                        // user: %11

%10 = alloc_stack $MyClass                      // users: %11, %13, %12

store %9 to %10 : $*MyClass                     // id: %11

%12 = apply %8<MyClass>(%10) : [email protected](method) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> ()

dealloc_stack %10 : $*MyClass                   // id: %13

%14 = integer_literal $Builtin.Int32, 0         // user: %15

%15 = struct $Int32 (%14 : $Builtin.Int32)      // user: %16

return %15 : $Int32                             // id: %16

} // end sil function ‘main‘

The bit that we‘re interested in here is this line:

%8 = function_ref @(extension in main):main.MyProtocol.testFuncA() -> () : [email protected](method) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> () // user: %12

The function_ref instruction gets a reference to a function known at compile-time. You can see that it‘s getting a reference to the function @(extension in main):main.MyProtocol.testFuncA() -> (), which is the method in the protocol extension. Thus Swift is using static dispatch.

Let‘s now take a look at what happens when we make the call like this:

let object: MyProtocol = MyClass()

object.testFuncA()

The main function now looks like this:

// main

sil @main : [email protected](c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 {

bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>):

alloc_global @main.object : main.MyProtocol  // id: %2

%3 = global_addr @main.object : main.MyProtocol : $*MyProtocol // users: %9, %4

// Create an opaque existential container and get its address (%4).

%4 = init_existential_addr %3 : $*MyProtocol, $MyClass // user: %8

// function_ref MyClass.__allocating_init()

%5 = function_ref @main.MyClass.__allocating_init() -> main.MyClass : [email protected](method) (@thick MyClass.Type) -> @owned MyClass // user: %7

%6 = metatype [email protected] MyClass.Type              // user: %7

%7 = apply %5(%6) : [email protected](method) (@thick MyClass.Type) -> @owned MyClass // user: %8

// Store the MyClass instance in the existential container.

store %7 to %4 : $*MyClass                      // id: %8

// Open the existential container to get a pointer to the MyClass instance.

%9 = open_existential_addr immutable_access %3 : $*MyProtocol to $*@opened("F199B87A-06BA-11E8-A29C-DCA9047B1400") MyProtocol // users: %11, %11, %10

// Dynamically lookup the function to call for the testFuncA requirement.

%10 = witness_method [email protected]("F199B87A-06BA-11E8-A29C-DCA9047B1400") MyProtocol, #MyProtocol.testFuncA!1 : <Self where Self : MyProtocol> (Self) -> () -> (), %9 : $*@opened("F199B87A-06BA-11E8-A29C-DCA9047B1400") MyProtocol : [email protected](witness_method) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> () // type-defs: %9; user: %11

// Call the function we looked-up for the testFuncA requirement.

%11 = apply %10<@opened("F199B87A-06BA-11E8-A29C-DCA9047B1400") MyProtocol>(%9) : [email protected](witness_method) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> () // type-defs: %9

%12 = integer_literal $Builtin.Int32, 0         // user: %13

%13 = struct $Int32 (%12 : $Builtin.Int32)      // user: %14

return %13 : $Int32                             // id: %14

} // end sil function ‘main‘

There are some key differences here.

An (opaque) existential container is created with init_existential_addr, and the MyClass instance is stored into it (store %7 to %4).

The existential container is then opened with open_existential_addr, which gets a pointer to the instance stored (the MyClass instance).

Then, witness_method is used in order to lookup the function to call for the protocol requirement MyProtocol.testFuncA for the MyClass instance. This will check the protocol witness table for MyClass‘s conformance, which is listed at the bottom of the generated SIL:

sil_witness_table hidden MyClass: MyProtocol module main {

method #MyProtocol.testFuncA!1: <Self where Self : MyProtocol> (Self) -> () -> () : @protocol witness for main.MyProtocol.testFuncA() -> () in conformance main.MyClass : main.MyProtocol in main // protocol witness for MyProtocol.testFuncA() in conformance MyClass

}

This lists the function @protocol witness for main.MyProtocol.testFuncA() -> (). We can check the implementation of this function:

// protocol witness for MyProtocol.testFuncA() in conformance MyClass

sil private [transparent] [thunk] @protocol witness for main.MyProtocol.testFuncA() -> () in conformance main.MyClass : main.MyProtocol in main : [email protected](witness_method) (@in_guaranteed MyClass) -> () {

// %0                                             // user: %2

bb0(%0 : $*MyClass):

%1 = alloc_stack $MyClass                       // users: %7, %6, %4, %2

copy_addr %0 to [initialization] %1 : $*MyClass // id: %2

// Get a reference to the extension method and call it.

// function_ref MyProtocol.testFuncA()

%3 = function_ref @(extension in main):main.MyProtocol.testFuncA() -> () : [email protected](method) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> () // user: %4

%4 = apply %3<MyClass>(%1) : [email protected](method) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> ()

%5 = tuple ()                                   // user: %8

destroy_addr %1 : $*MyClass                     // id: %6

dealloc_stack %1 : $*MyClass                    // id: %7

return %5 : $()                                 // id: %8

} // end sil function ‘protocol witness for main.MyProtocol.testFuncA() -> () in conformance main.MyClass : main.MyProtocol in main‘

and sure enough, its getting a function_ref to the extension method, and calling that function.

The looked-up witness function is then called after the witness_method lookup with the line:

%11 = apply %10<@opened("F199B87A-06BA-11E8-A29C-DCA9047B1400") MyProtocol>(%9) : [email protected](witness_method) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> () // type-defs: %9

So, we can conclude that dynamic protocol dispatch is used here, based on the use of witness_method.

We just breezed though quite a lot of technical details here; feel free to work through the SIL line-by-line, using the documentation to find out what each instruction does. I‘m happy to clarify anything you may be unsure about.

https://stackoverflow.com/questions/48422621/which-dispatch-method-would-be-used-in-swift

原文地址:https://www.cnblogs.com/feng9exe/p/9680924.html

时间: 2025-01-17 20:20:37

Which dispatch method would be used in Swift?的相关文章

Unused Method(不再使用的方法)——Dead Code(死亡代码)

    系列文章目录:     使用Fortify进行代码静态分析(系列文章) Unused Method(不再使用的方法)    示例:  1 private bool checkLevel(string abilitySeqno, string result) 2 { 3 return hrDutyexamProjectAbilityDS.CheckImportLevel(abilitySeqno, result); 4 }   Fortify解释: The method checkLeve

Using Swift with Cocoa and Objective-C(Swift 2.0版):开始--基础设置-备

这是一个正在研发的API或技术的概要文件,苹果公司提供这些信息主要是为了帮助你通过苹果产品使用这些技术或者编程接口而做好计划,该信息有可能会在未来发生改变,本文当中提到的软件应该以最终发布的操作系统测试和最终文档为准,未来有可能会提供新版本的文档信息. Swift 被设计用来无缝兼容 Cocoa 和 Objective-C .在 Swift 中,你可以使用 Objective-C 的 API(包括系统框架和你自定义的代码),你也可以在 Objective-C中 使用 Swift 的 API.这种

如何理解swift的导入过程

当我们新建一个xcode项目之后,我们可以在Swift里面导入任意Objective-C的Cocoa平台框架. 任意Objective-C的框架或者一些C的类库将会作为一个module(模块),直接导入到swift中,包括了所有的Objective-C系统的框架比如Foundation,UIKit还有SpriteKit等,就像系统支持公共的C类库.煮个栗子:如果我们想导入Foundation,只需要简单的添加import语句到我们写的Swift文件的顶部. import Foundation /

iOS开发之 Method Swizzling 深入浅出

<p align="center"><img src ="https://raw.githubusercontent.com/DotzuX/Notes/master/logo.jpeg"/></p> iOS开发之 Method Swizzling 深入浅出 只要善用Google,网上有很多关于Method Swizzling的Demo,在这里我就不打算贴代码了,主要介绍下概念,原理,注意事项等等. 开发需求 如果产品经理突然说:&

java 抽取 word,pdf 的四种武器

转自:https://www.ibm.com/developerworks/cn/java/l-java-tips/     感谢作者发布的文章 用 jacob 其实 jacob 是一个 bridage,连接 java 和 com 或者 win32 函数的一个中间件,jacob 并不能直接抽取 word,excel 等文件,需要自己写 dll 哦,不过已经有为你写好的了,就是 jacob 的作者一并提供了. jacob jar 与 dll 文件下载: http://www.matrix.org.

【转载】Java JDK 动态代理(AOP)使用及实现原理分析

转自:http://blog.csdn.net/jiankunking/article/details/52143504 版权声明:作者:jiankunking 出处:http://blog.csdn.net/jiankunking 本文版权归作者和CSDN共有 一.什么是代理? 代理是一种常用的设计模式,其目的就是为其他对象提供一个代理以控制对某个对象的访问.代理类负责为委托类预处理消息,过滤消息并转发消息,以及进行消息被委托类执行后的后续处理. 代理模式UML图: 简单结构示意图: 为了保持

访问祖先类的虚方法(直接访问祖先类的VMT,但是这种方法在新版本中未必可靠)

访问祖先类的虚方法 问题提出 在子类覆盖的虚方法中,可以用inherited调用父类的实现,但有时候我们并不需要父类的实现,而是想跃过父类直接调用祖先类的方法. 举个例子,假设有三个类,实现如下: type TClassA = class procedure Proc; virtual; end; TClassB = class(TClassA) procedure Proc; override; end; TClassC = class(TClassB) procedure Proc; ove

Selector

@selector is keyword in Objective-C. It could convert a method to a SEL type, which turns out behaving as a "function pointer". In the old Objective-C's age, selector is widely used, from setting the target-action to introspecting. In Objective-

源码分享!!!world文档转换为JPG图片

http://bbs.csdn.net/topics/390055515 —————————————————————————————————————————————————— 基本思路是:先将world转换为pdf,,在将pdf转换为JPG ..然后清空缓存,,删除PDF文件!! WordToPDF1.java package test; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; impor