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 T
and adds it to the party members in Party<T> 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 T
. We add the method to the body after the Party<T: AnimalProtocol where T: Equatable> {
public class declaration:
public func createAndAddMember(name: String) -> T {
let newMember = T(name: name)
addMember(newMember)
return newMember
}
The method uses the generic type T
and passes the name
argument to create a new instance called newMember
. Then, the code calls the addMember
method with newMember
as an argument and finally returns the recently...