O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Type erasure

In Chapter 3, Types and Type Casting we talked about Abstract versus Concrete types. Type erasure is a process to make abstract types such as Generics concrete.

Why we would want to do it? The answer is because we want to write code against contracts; in other words, we want to prefer composition over inheritance. Also, sometimes we would want to be more flexible with the types. This concept may sound complicated, so let's continue our example from the previous section to understand why and how we would create type-erased structures.

First, we want to examine if we can use CustomView type and create an array with CustomView elements. We will create a CustomView:

struct CustomDisabledButton: CustomView {  typealias ViewType = ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required