In Swift, a protocol is a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. Protocols define a list of methods and properties that any conforming class, structure or enumeration must implement.
Declaring a protocol in Swift is straightforward. Here is an example:
main.swift84 chars5 linesThis Animal protocol requires any conforming type to implement a name property of type String with both get and set accessors, and a makeSound() method that returns a String.
To conform to a protocol, you simply need to add the protocol name after the class, structure or enumeration name, separated by a colon. Here is an example:
main.swift171 chars12 linesThis Dog class conforms to the Animal protocol by implementing the required name property and makeSound() method.
Protocols can also be used in combination with delegates to enable communication between different parts of your code. You can use the protocol keyword to declare a delegate:
main.swift217 chars13 linesIn this example, the Example class has a delegate property of type ExampleDelegate. The ExampleDelegate protocol requires any conforming type to implement the didReceiveData(data:) method. By calling the delegate?.didReceiveData(data:) method, the Example class can communicate with any object that conforms to the ExampleDelegate protocol.
Finally, Swift allows protocols to inherit from other protocols, and you can use extensions to add functionality to existing protocols. These features give you more power and flexibility to create reusable and composable code.
gistlibby LogSnag