Breaking Down Type Erasure in Swift
Type Erasure Pattern
We can use the type erasure pattern to combine both generic type parameters and associated types to satisfy both the compiler and our flexibility goals.
We will need to create three discrete types in order to satisfy these constraints. This pattern includes an abstract base class, a private box class, and finally a public wrapper class. This same pattern, as diagramed below, is even used in the Swift standard library.

Abstract Base
The first step of the process is to create an abstract base class. This base class will have three requirements:
- Conform to the
Rowprotocol. - Define a generic type parameter
Modelthat serves asRow’s associated type. - Be abstract. (each function must be overridden by a subclass)
This class will not be used directly, but instead subclassed in order to bind the generic type constraint to our protocol’s associated type. We’ve marked this class private as well as by convention prefixing it with an _.
Private Box
Next we create a private Box class with these requirements:
- Inherit from the generic base class
_AnyRowBase. - Define a generic type parameter
Concretethat itself conforms toRow. - Store an instance of
Concretefor later usage. - Trampoline each
Rowprotocol function calls to the storedConcreteinstance.
This class is referred to as a Box class, because it holds a reference to our concrete implementer of the protocol. In our case this would be a FileCell, FolderCell or DetailFileCell all of which implement Row. We receive the Row protocol conformance from our super class _AnyRowBase and override each function by trampolining the call over to the concrete class. Finally, this class serves a conduit to connect our concrete class’s associated type with our base classes generic type parameter.
Public Wrapper
With our private implementation details in place, we need to create a public interface for our type erased wrapper. The naming convention used for this pattern is to prefix Any in front of the protocol you’re wrapping, in our case AnyRow.
This class has the following responsibilities:
- Conform to the
Rowprotocol. - Define a generic type parameter
Modelthat serves asRows associated type. - Within its initializer, take a concrete implementer of the
Rowprotocol. - Wrap the concrete implementer in a
privateBox_AnyRowBase<Model>. - Trampoline each
Rowfunction call along to the Box.
This final piece of the puzzle performs the actual type erasing. We supply the AnyRow class with a concrete implementer of Row (i.e. FileCell) and it erases that concrete type allowing us to work with simply any adopter of Row with matching associated types (i.e. AnyRow<File>).
Notice that while our concrete implementer is a property of type _AnyRowBase<Model>, we have to wrap it up in an instance of _AnyRowBox. The only requirement on _AnyRowBox’s initializer is that the concrete class implements Row. This is where the actual type easement occurs. Without this layer in our stack we’d be required to supply the associated type Model to _AnyRowBase<Model> explicitly; and we’d be back to square one.
The Payoff!
The biggest benefit to this process is all the messy boilerplate is an implementation detail. We are left with a relatively simple public API. Let’s revisit our original goals that are now possible with our type erased AnyRow<Model>.
Homogeneous Requirement
One important thing to note is we haven’t lost all of the conveniences and safety of strong typing. With Swift type checker still helping us out we cannot hold an array of just any AnyRow, our Model type must remain consistent.
This differs from how other more loosely typed languages such as Objective-C would handle the situation. The following is perfectly valid in Objective-C:
Swift, on the other hand, requires our array to be homogeneous around our protocol’s associated type. If we attempt the same line of code in Swift we’re presented with an error:
This is a good thing; we’re allowed enough flexibility to work with multiple types conforming to Row but we cannot be bitten by receiving a type we did not expect.
Wrapping Up
Assembling all the pieces required in the type erasure pattern can be overwhelming at first. Fortunately, it’s a formulaic process that will not differ based on your protocol. It’s such a systematic process that the Swift standard library may very well do this for you at some point. See the Swift Evolution’s Completing Generics Manifesto
To explore type erasure concepts in a Swift Playground, check out our accompanying Type Erasure Playgrounds:
https://www.bignerdranch.com/blog/breaking-down-type-erasures-in-swift/
Breaking Down Type Erasure in Swift的更多相关文章
- A “Type Erasure” Pattern that Works in Swift:类型域的转换
新视角:通过函数式编程的范畴理论来看待这个问题会更容易理解: 在低层类型无法很好表达的类型,可以将其转化为高阶类型进行表示. 将协议的实现类型转化为monad类型: 解决将具有关联类型的协议当作类型的 ...
- 关于type erasure
哇,好久没有写blog了,再不写的话,blog的秘密都要忘记了,嘿嘿. 最近在试着参与一个开源项目,名字叫avim(A Vibrate IM),别想多了哟.地址是:https://github.com ...
- Java魔法堂:解读基于Type Erasure的泛型
一.前言 还记得JDK1.4时遍历列表的辛酸吗?我可是记忆犹新啊,那时因项目需求我从C#转身到Java的怀抱,然后因JDK1.4少了泛型这样语法糖(还有自动装箱.拆箱),让我受尽苦头啊,不过也反映自己 ...
- Type Erasure with Pokemon---swift的类型擦除
我感觉这个是swift的设计缺陷. 类型擦除:解决泛型类型作为公用类型的问题 是抽象的公用机制的一种实现方式. 1)类型擦除并不能解决类型不一致的兼容问题,只能解决类似继承一致性的兼容问题. 2)擦除 ...
- Swift安装
Server1 .Update sudo apt-get update sudo apt-get upgrade . sudo apt-get install bridge-utils .IP 3.1 ...
- swift中文文档- 类型转换
未翻译完 待续(英语烂,求斧正) Type Casting 类型转换 Type casting is a way to check the type of an instance, and/or to ...
- OpenStack Swift集群与Keystone的整合使用说明
之前已经介绍了OpenStack Swift集群和Keystone的安装部署,最后来讲一讲Swift集群与Keystone的整合使用吧. 1. 简介 本文档描述了Keystone与Swift集群的整合 ...
- Using Swift with Cocoa and Objective-C(Swift 2.0版):开始--基础设置-备
这是一个正在研发的API或技术的概要文件,苹果公司提供这些信息主要是为了帮助你通过苹果产品使用这些技术或者编程接口而做好计划,该信息有可能会在未来发生改变,本文当中提到的软件应该以最终发布的操作系统测 ...
- 那些年,学swift踩过的坑
最近在学swift,本以为多是语法与oc不同,而且都是使用相同的cocoa框架,相同的API,但是或多或少还是有些坑在里,为了避免以后再踩,在这里记下了,以后发现新的坑,也会慢慢在这里加上 [TOC] ...
随机推荐
- MVC会员注销功能Cookie的应用
我们实现了<MVC应用程序实现会员登录功能>http://www.cnblogs.com/insus/p/3466512.html 有登录就会有注销功能.此次Insus.NET练习一个MV ...
- MVC使用jQuery.ajax()删除数据
jQuery.ajax()可以简写为$.ajax().以前有写过MVC删除的实现,如<MVC实现删除数据库记录> http://www.cnblogs.com/insus/p/336804 ...
- sqlserver查询连续签到天数
create table #t(keyId int identity,actionDate datetime)insert into #t(actionDate) select distinct Cr ...
- c++ 重载、覆盖 (隐藏)(virtual)
背景:不用说,学习C++的你,一定知道这是个词--至于难不难懂,就看你的理解能力了,我理解也是费劲千辛万苦啊,成员函数的重载.覆盖(override).隐藏.virtual 很容易混淆,C++程序员必 ...
- Jquery自定义动画与动画队列
animate:自定义动画 $(selector).animate({params},[speed],[easing],[callback]); params:要执行动画的css属性,它是一个对象可以 ...
- Codeforces445B(SummerTrainingDay06-N 并查集)
B. DZY Loves Chemistry time limit per test:1 second memory limit per test:256 megabytes input:standa ...
- python学习之老男孩python全栈第九期_数据库day005知识点总结 —— MySQL数据库day5
三. MySQL视图(不常用) 给某个查询语句设置个别名(视图名),日后方便使用 - 创建: create view 视图名 as SQL; PS:视图是虚拟的 - 修改: alter view 视图 ...
- python内置函数每日一学 -- any()
any(iterable) 官方文档解释: Return True if any element of the iterable is true. If the iterable is empty, ...
- 关于对DI和IOC的概念理解
在spring框架学习过程中,涉及到两个新名词:DI和IOC.开始总是混淆两者的概念,稀里糊涂,后来上网搜了一下又和同学讨论之后,基本上理解了二者的概念.实际上DI(依赖注入)和IOC(控制反转)就是 ...
- 【VS2015】Win7 X64上面安装VS2015
环境: 1.Win7 x64 SP1旗舰版 2.VS2015专业版Update3 3.IE11 4.WDK10 5.SDK10 安装步骤: 1.安装IE11,需要如下补丁: a.Windo ...