Combining initializer requirements in protocols with generic types
We included an initializer requirement when we declared the AnimalProtocol
protocol, so we know the necessary arguments to create an instance of any class that conforms to this protocol. We will add a new method that creates an instance of the generic type AnimalElement
and adds it to the party members in the Party<AnimalElement>
class.
The following lines show the code for the new createAndAddMember
method that receives a name
String
argument and returns an instance of the generic type AnimalElement
. We add the method to the body of the Party<AnimalElement: AnimalProtocol> where AnimalElement: Equatable
open class declaration. The code file for the sample is included in the swift_3_oop_chapter_06_07
folder:
open func createAndAddMember(name: String) -> AnimalElement {
let newMember = AnimalElement(name: name)
add(member: newMember)
return newMember
...