Generics

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

Generics

Functions

You can follow along with this section by creating a blank iOS playground in Xcode. Replace the boilerplate with this code:

Generic Types

All Swift collections are generic types. For example, this array initializer creates an array containing the elements of a sequence:

Creating a Generic Type

Here’s a generic struct you could use to store and retrieve any type from UserDefaults:

Extending a Generic Type

You can extend generic types the same way you can extend a normal class, struct, enum, or protocol. In the extension of a generic type, you have access to its type parameters:

See forum comments
Download course materials from Github
Previous: Generics - Introduction Next: Constraints