Swift protocol extension method is called instead of method implemented in subclass
Swift protocol extension method is called instead of method implemented in subclass
protocol MyProtocol {
func methodA()
func methodB()
}
extension MyProtocol {
func methodA() {
print("Default methodA")
}
func methodB() {
methodA()
}
}
// Test 1
class BaseClass: MyProtocol {
}
class SubClass: BaseClass {
func methodA() {
print("SubClass methodA")
}
}
let object1 = SubClass()
object1.methodB()
//
// Test 2
class JustClass: MyProtocol {
func methodA() {
print("JustClass methodA")
}
}
let object2 = JustClass()
object2.methodB()
//
// Output
// Default methodA
// JustClass methodA
This is just how protocols currently dispatch methods.
A protocol witness table (see this WWDC talk for more info) is used in order to dynamically dispatch to implementations of protocol requirements upon being called on a protocol-typed instance. All it is, is really just a listing of the function implementations to call for each requirement of the protocol for a given conforming type.
Each type that states its conformance to a protocol gets its own protocol witness table. You'll note that I said "states its conformance", and not just "conforms to". BaseClass gets its own protocol witness table for conformance to MyProtocol. However SubClass does not get its own table for conformance to MyProtocol – instead, it simply relies on BaseClass's. If you moved the
: MyProtocol down to the definition of SubClass, it would get to have its own PWT.
So all we have to think about here is what the PWT for BaseClass looks like. Well, it doesn't provide an implementation for either of the protocol requirements methodA() or methodB() – so it relies on the implementations in the protocol extension. What this means is that the PWT for BaseClass conforming to MyProtocol just contains mappings to the extension methods.
So, when the extension methodB() method is called, and makes the call out to methodA(), it dynamically dispatches that call through the PWT (as it's being called on a protocol-typed instance; namely self). So when this happens with a SubClass instance, we're going through BaseClass's PWT. So we end up calling the extension implementation of methodA(), regardless of the fact that SubClass provides an implementation of it.
Now let's consider the PWT of JustClass. It provides an implementation of methodA(), therefore its PWT for conformance to MyProtocol has that implementation as the mapping for methodA(), as well as the extension implementation for methodB(). So when methodA() is dynamically dispatched via its PWT, we end up in its implementation.
As I say in this Q&A, this behaviour of subclasses not getting their own PWTs for protocols that their superclass(es) conform to is indeed somewhat surprising, and has been filed as a bug. The reasoning behind it, as Swift team member Jordan Rose says in the comments of the bug report, is
Therefore if this was the behaviour, already-compiled subclasses would lack any PWTs from superclass conformances that were added after the fact in another module, which would be problematic.
As others have already said, one solution in this case is to have BaseClass provide its own implementation of methodA(). This method will now be in BaseClass's PWT, rather than the extension method.
Although of course, because we're dealing with classes here, it won't just be BaseClass's implementation of the method that's listed – instead it will be a thunk that then dynamically dispatches through the class' vtable (the mechanism by which classes achieve polymorphism). Therefore for a SubClass instance, we'll wind up calling its override of methodA().
https://stackoverflow.com/questions/44703205/swift-protocol-extension-method-is-called-instead-of-method-implemented-in-subcl
Swift protocol extension method is called instead of method implemented in subclass的更多相关文章
- Swift 使用Extension 场景 浅析
别人一看到我的 Swift 代码,立刻就会问我为什么如此频繁的使用 extension.这是前几天在我写的另一篇文章中收到的评论: 我大量使用 extension 的主要目的是为了提高代码可读性.以下 ...
- swift protocol 与类继承结合时的bug
protocol CommonTrait: class { func commonBehavior() -> String } extension CommonTrait { func comm ...
- (细节控)swift3.0与融云IMKIT开发问题(一部分) override func onSelectedTableRow Method does not override any method from its superclass
原官网文档方案如下,在swift3.0的情况下出现 override func onSelectedTableRow Method does not override any method from ...
- org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method test() on null context object
前言 本文中提到的解决方案,源码地址在:springboot-thymeleaf,希望可以帮你解决问题. 至于为什么已经写了一篇文章thymeleaf模板引擎调用java类中的方法,又多此一举的单独整 ...
- 【iOS】Swift扩展extension和协议protocol
加上几个关节前Playground摘要码进入github在,凝视写了非常多,主要是为了方便自己的未来可以Fanfankan. Swift语法的主要部分几乎相同的. 当然也有通用的.运算符重载.ARC. ...
- swift protocol 见证容器 虚函数表 与 动态派发
一.测试代码: //protocol DiceGameDelegate: AnyObject { //} // //@objc protocol OcProtocol{ // @objc fun ...
- swift protocol的几种形式
三个关注点:1.形式:2.实现方式:3.使用方式: 一.基本形式: 形式:内部无泛型类型: 实现:只需指定类型和实现相应的功能即可: 使用:可以用在其他类型出现的任何地方: protocol Resp ...
- Swift 扩展(Extension)总结
概要 扩展是给已经存在的类(class),结构体(structure),枚举类型(enumeration)和协议(protocol)增加新的功能.类似Objective-C中的Category,不同的 ...
- swift class extension 与继承
1.扩展中无法继承重写已有函数,不能添加函数. Extensions can add new functionality to a type, but they cannot override exi ...
随机推荐
- POJ2912 Rochambeau —— 种类并查集 + 枚举
题目链接:http://poj.org/problem?id=2912 Rochambeau Time Limit: 5000MS Memory Limit: 65536K Total Submi ...
- Oracle 删除用户和表空间////Oracle创建删除用户、角色、表空间、导入导出、...命令总结/////Oracle数据库创建表空间及为用户指定表空间
Oracle 使用时间长了, 新增了许多user 和tablespace. 需要清理一下 对于单个user和tablespace 来说, 可以使用如下命令来完成. 步骤一: 删除user drop ...
- 【183】VMware + CentOS 安装教程等
目录: VMware 虚拟机安装 虚拟机上安装 CentOS VMware Tools 安装 为程序增加环境变量 其他 1. VMware 虚拟机安装 ※ 参考:VMware 虚拟机安装使用教程( ...
- 解决axios IE11 Promise对象未定义
在你的项目中安装polyfill Babel Polyfill 按照官网方法安装并引入即可 http://blog.csdn.net/panyox/article/details/76377248
- Pow(x, n) 位运算总结 典型
https://leetcode.com/problems/powx-n/ Implement pow(x, n), which calculates x raised to the power n ...
- 开源可扩展的Web视频播放器:Clappr Player
http://www.open-open.com/lib/view/open1417057033846.html http://www.csdn.net/article/2014-11-27/2822 ...
- Objective-C NSData/NSMutableData
创建于完成: 2018/02/06 总览: http://www.cnblogs.com/lancgg/p/8404975.html 数据类 简介 处理比特列 Foundation/NSData ...
- [App Store Connect帮助]八、维护您的 App(4.3)回复顾客评论(iOS、macOS 或 watchOS)
您可以公开回复顾客评论,但在您的 App Store 产品页上每条评论仅会显示一条回复.您可以回复评论.编辑回复,以及删除回复. 在回复和编辑显示在 App Store 上之前(可能需要至多 24 小 ...
- linux 磁盘 分区、格式化、挂载
将容量结果易读的容量格式显示出来df -h 分区 初次接触仅分成两个分区(“/与Swap”)预留一个备用的剩余磁盘容量 磁盘分区 fdisk #df /找出磁盘文件名#fdisk /dev/hdc#m ...
- Hdu 3605 Escape (最大流 + 缩点)
题目链接: Hdu 3605 Escape 题目描述: 有n个人要迁移到m个星球,每个星球有最大容量,每个人有喜欢的星球,问是否所有的人都能迁移成功? 解题思路: 正常情况下建图,不会爆内存,但是T ...