-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Learning Swift Second Edition
By :

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.
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 might be to declare Element
as a placeholder for your individual methods:
extension Array { func someMethod<Element>(element: Element) { // ... } }
This is more dangerous because the compiler doesn't detect...
Change the font size
Change margin width
Change background colour