We will create an AnimalProtocol
protocol to specify the requirements that a type must meet in order to be considered an animal. Then, we will create an Animal
base class that conforms to this protocol, and then, we will specialize this class in three subclasses: Dog
, Frog
, and Lion
. Then, we will create a Party
class that will be able to work with the instances of any class that conforms to the AnimalProtocol
protocol through generics. We will work with a party of dogs, a party of frogs, and a party of lions.
Then, we will create a DeeJayProtocol
protocol and generate a HorseDeeJay
class that conforms to this new protocol. We will create a subclass of the Party
class named PartyWithDeeJay
, which will use generics to work with the instances of any type that conforms to the AnimalProtocol
protocol and the instances of any type that conforms to the DeeJaypProtocol
interface. We will work with a party of dogs with a DJ.
Now, it is time to code one of the protocols that will be used as a constraint later when we define the class that takes advantage of generics. The following lines show the code for the AnimalProtocol
protocol. The public
modifier followed by the protocol
keyword and the protocol name, AnimalProtocol
, composes the protocol declaration. The first line of code imports Foundation
because we will need this import for other classes that we will add later. The code file for the sample is included in the swift_3_oop_chapter_06_01
folder:
import Foundation
public protocol AnimalProtocol {
var name: String { get }
init (name: String)
func dance()
func say(message: String)
func sayGoodbyeTo(destination: AnimalProtocol)
func sayWelcomeTo(destination: AnimalProtocol)
func sing()
}
The protocol declares a read-only name: String
stored property and five method requirements: dance
, say
, sayGoodbyeTo
, sayWelcomeTo
, and sing
. As you learned in the previous chapter, the protocol includes only the method declaration because the classes that conform to AnimalProtocol
are responsible for providing the implementation of the name
stored or computed property and the other five methods.
In addition, the protocol specifies an initializer requirement. The initializer requires a name argument, so we will make sure that we will be able to create an instance of any class that conforms to this protocol by providing a value to a name argument during initialization. The following line specifies the initializer requirement:
init (name: String)
3.147.42.193