Extending the existing generics
The two main generics we probably want to extend are arrays and dictionaries. These are the two most prominent containers provided by Swift and they 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.
Enhancing arrays
Knowing that an array is declared as the struct Array<T>
, your first instinct is probably to extend an array that might look something like this:
extension Array<T> { // error: Generic arguments are not allowed on an extension // ... }
However, as you can see, you would get an error. Instead, you can simply leave out the placeholder specification and still use the T
placeholder inside your implementations. Your other instinct might be to declare T
as a placeholder for your individual methods:
extension Array { func someMethod<T>() { // ... } }
This is more dangerous because the compiler doesn't give an error. This is wrong...