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的更多相关文章

  1. Swift 使用Extension 场景 浅析

    别人一看到我的 Swift 代码,立刻就会问我为什么如此频繁的使用 extension.这是前几天在我写的另一篇文章中收到的评论: 我大量使用 extension 的主要目的是为了提高代码可读性.以下 ...

  2. swift protocol 与类继承结合时的bug

    protocol CommonTrait: class { func commonBehavior() -> String } extension CommonTrait { func comm ...

  3. (细节控)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 ...

  4. org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method test() on null context object

    前言 本文中提到的解决方案,源码地址在:springboot-thymeleaf,希望可以帮你解决问题. 至于为什么已经写了一篇文章thymeleaf模板引擎调用java类中的方法,又多此一举的单独整 ...

  5. 【iOS】Swift扩展extension和协议protocol

    加上几个关节前Playground摘要码进入github在,凝视写了非常多,主要是为了方便自己的未来可以Fanfankan. Swift语法的主要部分几乎相同的. 当然也有通用的.运算符重载.ARC. ...

  6. swift protocol 见证容器 虚函数表 与 动态派发

    一.测试代码: //protocol DiceGameDelegate: AnyObject { //} // //@objc protocol OcProtocol{ //    @objc fun ...

  7. swift protocol的几种形式

    三个关注点:1.形式:2.实现方式:3.使用方式: 一.基本形式: 形式:内部无泛型类型: 实现:只需指定类型和实现相应的功能即可: 使用:可以用在其他类型出现的任何地方: protocol Resp ...

  8. Swift 扩展(Extension)总结

    概要 扩展是给已经存在的类(class),结构体(structure),枚举类型(enumeration)和协议(protocol)增加新的功能.类似Objective-C中的Category,不同的 ...

  9. swift class extension 与继承

    1.扩展中无法继承重写已有函数,不能添加函数. Extensions can add new functionality to a type, but they cannot override exi ...

随机推荐

  1. 什么叫强类型的DATASET ?对DATASET的操作处理?强类型DataSet的使用简明教程

    强类型DataSet,是指需要预先定义对应表的各个字段的属性和取值方式的数据集.对于所有这些属性都需要从DataSet, DataTable, DataRow继承,生成相应的用户自定义类.强类型的一个 ...

  2. 数据库sqlite3的使用-代码实例应用

      一.使用代码的方式批量添加(导入)数据到数据库中 1.执行SQL语句在数据库中添加一条信息 插入一条数据的sql语句: 点击run执行语句之后,刷新数据 2.在ios项目中使用代码批量添加多行数据 ...

  3. django flask缓存memcache的key生成方法介绍

    去年的一个django项目中,使用了memcache作为系统缓存,并实现多台机器上的缓存共享.配置的cache如下图所示: 最近在项目调试过程中,发现memcache在进行缓存时,使用的key并不是实 ...

  4. bzoj4881 线段游戏——上升序列方案数

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4881 连题意都转化不了了... 题意是要求从一个数列中选出两个上升序列的方案数: 先判断是否 ...

  5. 手把手VirtualBox虚拟机下安装rhel6.4 linux位系统详细文档

    使用Virtual Box,感觉跟Vmware差不多,我的本子的系统是win7 64位. 下面演示安装的是在VirtualBox里安装rhel 6.4 linux 32位系统.32位系统安装和 64位 ...

  6. JAVA THINGKING (二)随笔

    1. 基本数据员的默认值 Boolean false Char '\u0000'(null) byte (byte)0 short  (short)0 int  0 long 0L float 0.0 ...

  7. lua 与C通过c api传递table

    此文转自http://blog.csdn.net/perfect2011/article/details/19200511(感谢...) 首先了解下c++与lua之间的通信: 假设在一个lua文件中有 ...

  8. 不让浏览器缓存input的值

    方法一: 在不想使用缓存的input中添加 autocomplete="off"eg: <input type="text" autocomplete=& ...

  9. poj 2398 Toy Storage【二分+叉积】

    二分点所在区域,叉积判断左右 #include<iostream> #include<cstdio> #include<cstring> #include<a ...

  10. 初学者的疑惑,到底什么是javaBean?

    JavaBeans是Java中一种特殊的类,可以将多个对象封装到一个对象(bean)中.特点是可序列化,提供无参构造器,提供getter方法和setter方法访问对象的属性.名称中的"Bea ...