Swift - 实例对象调用协议方法优先级分析/ witness_methos witness_table分析

简介: 本文主要探究:当一个类遵循了协议,且协议和类都有方法实现时,实例对象调用方法的优先顺序

代码示例1:


image.png

WX20211211-162957@2x.png


转为SIL源码查看:swiftc -emit-sil main.swift | xcrun swift-demangle >> ./main.sil


main函数


protocol YRProtocol {
 func teach()
}
extension YRProtocol {
 func teach()
}
class YRTeach : YRProtocol {
 func teach()
 @objc deinit
 init()
}
@_hasStorage @_hasInitialValue var object1: YRProtocol { get set }
@_hasStorage @_hasInitialValue var object2: YRTeach { get set }
// object1
sil_global hidden @main.object1 : main.YRProtocol : $YRProtocol
// object2
sil_global hidden @main.object2 : main.YRTeach : $YRTeach
// main
sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 {
bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>):
 alloc_global @main.object1 : main.YRProtocol // id: %2
 %3 = global_addr @main.object1 : main.YRProtocol : $*YRProtocol // users: %9, %7
 %4 = metatype $@thick YRTeach.Type              // user: %6
 // function_ref YRTeach.__allocating_init()
 %5 = function_ref @main.YRTeach.__allocating_init() -> main.YRTeach : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: %6
 %6 = apply %5(%4) : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: %8
 %7 = init_existential_addr %3 : $*YRProtocol, $YRTeach // user: %8
 store %6 to %7 : $*YRTeach                      // id: %8
 %9 = begin_access [read] [dynamic] %3 : $*YRProtocol // users: %12, %11
 %10 = alloc_stack $YRProtocol                   // users: %17, %16, %13, %11
 copy_addr %9 to [initialization] %10 : $*YRProtocol // id: %11
 end_access %9 : $*YRProtocol                    // id: %12
 %13 = open_existential_addr immutable_access %10 : $*YRProtocol to $*@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol // users: %15, %15, %14
 %14 = witness_method $@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol, #YRProtocol.teach : <Self where Self : YRProtocol> (Self) -> () -> (), %13 : $*@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol : $@convention(witness_method: YRProtocol) <τ_0_0 where τ_0_0 : YRProtocol> (@in_guaranteed τ_0_0) -> () // type-defs: %13; user: %15
 %15 = apply %14<@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol>(%13) : $@convention(witness_method: YRProtocol) <τ_0_0 where τ_0_0 : YRProtocol> (@in_guaranteed τ_0_0) -> () // type-defs: %13
 destroy_addr %10 : $*YRProtocol                 // id: %16
 dealloc_stack %10 : $*YRProtocol                // id: %17
 alloc_global @main.object2 : main.YRTeach      // id: %18
 %19 = global_addr @main.object2 : main.YRTeach : $*YRTeach // users: %23, %24
 %20 = metatype $@thick YRTeach.Type             // user: %22
 // function_ref YRTeach.__allocating_init()
 %21 = function_ref @main.YRTeach.__allocating_init() -> main.YRTeach : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: %22
 %22 = apply %21(%20) : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: %23
 store %22 to %19 : $*YRTeach                    // id: %23
 %24 = begin_access [read] [dynamic] %19 : $*YRTeach // users: %25, %27
 %25 = load %24 : $*YRTeach                      // users: %30, %28, %29, %26
 strong_retain %25 : $YRTeach                    // id: %26
 end_access %24 : $*YRTeach                      // id: %27
 %28 = class_method %25 : $YRTeach, #YRTeach.teach : (YRTeach) -> () -> (), $@convention(method) (@guaranteed YRTeach) -> () // user: %29
 %29 = apply %28(%25) : $@convention(method) (@guaranteed YRTeach) -> ()
 strong_release %25 : $YRTeach                   // id: %30
 %31 = integer_literal $Builtin.Word, 1          // user: %33
 // function_ref _allocateUninitializedArray<A>(_:)
 %32 = function_ref @Swift._allocateUninitializedArray<A>(Builtin.Word) -> ([A], Builtin.RawPointer) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %33
 %33 = apply %32<Any>(%31) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // users: %35, %34
 %34 = tuple_extract %33 : $(Array<Any>, Builtin.RawPointer), 0 // user: %46
 %35 = tuple_extract %33 : $(Array<Any>, Builtin.RawPointer), 1 // user: %36
 %36 = pointer_to_address %35 : $Builtin.RawPointer to [strict] $*Any // user: %43
 %37 = string_literal utf8 "end"                 // user: %42
 %38 = integer_literal $Builtin.Word, 3          // user: %42
 %39 = integer_literal $Builtin.Int1, -1         // user: %42
 %40 = metatype $@thin String.Type               // user: %42
 // function_ref String.init(_builtinStringLiteral:utf8CodeUnitCount:isASCII:)
 %41 = function_ref @Swift.String.init(_builtinStringLiteral: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) -> Swift.String : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // user: %42
 %42 = apply %41(%37, %38, %39, %40) : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // user: %44
 %43 = init_existential_addr %36 : $*Any, $String // user: %44
 store %42 to %43 : $*String                     // id: %44
 // function_ref _finalizeUninitializedArray<A>(_:)
 %45 = function_ref @Swift._finalizeUninitializedArray<A>(__owned [A]) -> [A] : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // user: %46
 %46 = apply %45<Any>(%34) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // users: %55, %52
 // function_ref default argument 1 of print(_:separator:terminator:)
 %47 = function_ref @default argument 1 of Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> () : $@convention(thin) () -> @owned String // user: %48
 %48 = apply %47() : $@convention(thin) () -> @owned String // users: %54, %52
 // function_ref default argument 2 of print(_:separator:terminator:)
 %49 = function_ref @default argument 2 of Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> () : $@convention(thin) () -> @owned String // user: %50
 %50 = apply %49() : $@convention(thin) () -> @owned String // users: %53, %52
 // function_ref print(_:separator:terminator:)
 %51 = function_ref @Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> () : $@convention(thin) (@guaranteed Array<Any>, @guaranteed String, @guaranteed String) -> () // user: %52
 %52 = apply %51(%46, %48, %50) : $@convention(thin) (@guaranteed Array<Any>, @guaranteed String, @guaranteed String) -> ()
 release_value %50 : $String                     // id: %53
 release_value %48 : $String                     // id: %54
 release_value %46 : $Array<Any>                 // id: %55
 %56 = integer_literal $Builtin.Int32, 0         // user: %57
 %57 = struct $Int32 (%56 : $Builtin.Int32)      // user: %58
 return %57 : $Int32                             // id: %58
} // end sil function 'main'


查看main源码知道,生成的object1通过witness_method调用了YRProtocol.Teach方法


image.png

2131639212958_.pic.jpg


witness_method的官方说明:


image.png

WX20211211-170352@2x.png


witness_method 表示在witness_table中查询协议方法的实现并调用


此处我们在SIL源码中查找YRProtocol协议的witness_table方法


sil_vtable YRTeach {
  #YRTeach.teach: (YRTeach) -> () -> () : @main.YRTeach.teach() -> ()   // YRTeach.teach()
  #YRTeach.init!allocator: (YRTeach.Type) -> () -> YRTeach : @main.YRTeach.__allocating_init() -> main.YRTeach  // YRTeach.__allocating_init()
  #YRTeach.deinit!deallocator: @main.YRTeach.__deallocating_deinit  // YRTeach.__deallocating_deinit
}
sil_witness_table hidden YRTeach: YRProtocol module main {
  method #YRProtocol.teach: <Self where Self : YRProtocol> (Self) -> () -> () : @protocol witness for main.YRProtocol.teach() -> () in conformance main.YRTeach : main.YRProtocol in main   // protocol witness for YRProtocol.teach() in conformance YRTeach
}


witness_table中我们发现确实有定义YRProtocol.teach()方法


然后查看YRProtocol.teach()的具体实现


image.png

WX20211211-171715@2x.png


总结1. 当protocol中声明了方法时,源码做了如下操作:


  1. witness_table中存放协议方法


  1. 实例对象调用协议方法时,编译器会通过witness_method这个方法去 witness_m ethod表中查找对应协议方法并调用


  1. 协议方法的实现,本质是调用遵循了协议的类里协议方法的实现(通过class_method在sil_vtable中查询),而并不会调用协议拓展里的方法实现


2. 代码示例2:


image.png

WX20211211-172619@2x.png


此时发现打印变了,打印了YRProtocol extension里的方法,查看SIL源码:


image.png

WX20211211-173217@2x.png


同时,源码中也没有witness_table中也没有方法声明和实现


image.png

WX20211211-173448@2x.png


总结2:


当protocol中没有声明方法时,witness_table中没有协议方法的声明,编译器会调用协议 extension中的方法实现


总结:


  1. 当协议中有方法声明时(witness_table有声明),


  • 类中有方法实现:  实例对象优先调用类中的方法实现
  • 类中没有方法实现: 实例对象调用协议拓展中的方法实现


  1. 当协议中没有方法声明时(witness_table没有声明):


实例对象总是调用协议拓展中的方法实现


参考:


官方文档:witness_method


官方文档:witness_table


相关文章
|
6月前
|
Swift iOS开发
Swift 语言: 什么是协议(Protocol)?如何实现和使用协议?
Swift 语言: 什么是协议(Protocol)?如何实现和使用协议?
189 2
|
算法 Swift C++
34 Swift为了协议 关联类型
Swift为了协议 关联类型
71 0
|
存储 Swift iOS开发
31 Swift 继续聊聊协议扩展
Swift 继续聊聊协议扩展
107 0
|
10天前
|
Swift iOS开发
Swift 方法
10月更文挑战第29天
15 4
|
7天前
|
存储 Swift 开发者
Swift 协议
Swift 协议
16 0
|
6月前
|
设计模式 Swift iOS开发
【Swift开发专栏】Swift中的协议与委托模式
【4月更文挑战第30天】Swift编程语言强调协议与委托模式。协议定义了类型需实现的方法和属性,如`SomeProtocol`示例。遵循协议的类、结构体或枚举需实现协议要求。协议可继承,也可作为类型使用。委托模式让对象间通信更灵活,通过协议实现,如`DataSourceDelegate`示例。实战案例展示了在`UITableView`和自定义下载器中使用委托模式。
118 0
|
4月前
|
存储 Swift
Swift之struct二进制大小分析
【7月更文挑战第18天】Swift 中 `struct` 的二进制大小分析: `struct` 作为值类型, 其内存布局和大小由成员变量决定。基本类型如 `Int`, `Double`, `Bool` 存储大小固定; 复合类型如数组大小取决于元素数量及类型。示例 `struct` 包含 `Int`, `Double`, `Bool`, 和 `[String]`。`Int` 和 `Double` 各占 8 字节, `Bool` 占 1 字节, 数组大小根据字符串存储开销变化。还需考虑内存对齐以优化访问效率。综上, 分析 `struct` 大小需考量多种因素。
|
5月前
|
Swift C++ 索引
Swift开发——简单函数实例
函数是编程的基础,用于封装特定功能的代码。它们有关键词func、函数名、参数列表(可为空)和返回类型。多返回值可通过元组、数组、inout参数或可选类型实现。例如,返回元组 `(value1, value2)`,数组 `[value1, value2]` 或使用可选数组 `[[Double]]?`。函数可以作为其他函数的参数,类似闭包或Lambda表达式。在Swift中,示例展示了通过元组、带索引的元组、数组和可选类型返回多个值的函数。还演示了如何使用inout参数交换变量值。
105 5
Swift开发——简单函数实例
|
4月前
|
存储 安全 Swift
Swift高级特性:泛型与协议
【7月更文挑战第10天】Swift高级特性:泛型与协议增强代码复用与类型安全。泛型允许编写通用代码,如`swap`函数和泛型`Stack`结构体,支持类型约束如`Comparable`。协议定义行为蓝图,类型遵循协议需实现其要求。通过两者结合,构建高效灵活的代码结构。
|
6月前
Swift4.0判断本函数是否在其它类有相同的方法
Swift4.0判断本函数是否在其它类有相同的方法
43 0