Member-only story

Type Erasure in Swift

Slacktime
4 min readAug 9, 2017

--

Introduction

Swift is heavily influenced by different programming paradigms from functional, imperative and object-oriented programming. This allows you as a developer to write very powerful and flexible code.

Protocol oriented programming in Swift helps you to bypass problems of object oriented-programming surrounding inheritance and their undesired complexity. But protocols still struggle with some compiler limitations when it comes to the usage of generic types. Type erasure is a pattern that can help us to bypass these limitations.

Protocol-oriented programming was featured by Apple on a WWDC 2015 presentation. Even if it’s from 2015 and focussed on Swift 2 it’s still worth watching and one of the best WWDC videos!

Protocols & Associated Types

A major goal of protocols is to provide a blueprint of properties, functions and their requirements for a particular task. To be less error-prone, Swift checks this interface at compile time. So if you want to conform to a certain protocol, you have to fill in the required properties and functions. This provides you with a lot of safety but also some limitations.

--

--

Written by Slacktime

I’m Chris, a software engineer from Düsseldorf, DE・In my slacktime I like to write about topics and experiences around mobile app development and agile working.

Responses (1)

Write a response