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 
    } 

The method uses the generic type AnimalElement and passes the name argument to create a new instance called newMember. Then, the code calls the add method with newMember as the member argument and finally returns the recently created instance.

The following lines call the recently added createAndAddMember method to create and add a new Lion instance with the name initialized to King to the lionsParty Party<Lion> instance. Then, the next line calls the say method for the returned instance. The code file for the sample is included in the swift_3_oop_chapter_06_07 folder:

    let king = lionsParty.createAndAddMember(name: "King") 
    king.say(message: "My name is King") 

The next lines show the output generated when we enter the previous lines at the end of our Playground:

Simba welcomes King: Rrroarrr
King says: My name is King
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.145.109