Extending generics

The two main generics that we will probably want to extend are arrays and dictionaries. These are the two most prominent containers provided by Swift and are used in virtually every app. Extending a generic type is simple once you understand that an extension itself does not need to be generic.

Adding methods to all forms of a generic

Knowing that an array is declared as struct Array<Element>, your first instinct to extend an array might look something similar to this:

extension Array<Element> { // Use of undeclared type 'Element'
    // ...
}

However, as you can see, you would get an error. Instead, you can simply leave out the placeholder specification and still use the Element placeholder inside your implementations. Your other instinct ...

Get Swift: Developing iOS Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.