Type Erasure

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Type Erasure

Protocol With Associated Type

A protocol with associated type (PAT) is like a generic protocol, but the generic type is one of the protocol’s requirements. It gives you a placeholder name to use in the rest of the protocol definition.

Type Erasure

When you want to use a PAT (or any generic type) as a concrete type, you must employ type erasure: Convert a PAT into a concrete type by removing type information. Type erasure hides a generic type in a non-generic type that’s easier to use in your code. You’ll often want to use a PAT as a type, like this:

Primary Associated Types

Here’s another feature introduced in Swift 5.7: You can declare one or more of your protocol’s associated types as its primary associated types by including them in angle brackets:

See forum comments
Download course materials from Github
Previous: Combining Protocols Next: Types