I wanted to write a bit about Generics in Swift, but I realized that some of the major powers of Generics require the use of protocols, so I felt I should start by talking about them first.
In Swift, protocols are basically a named contract that your classes can conform to. If your class says it conforms to Equatable, then it better fulfill all of the required functionality to make it equatable. They are rather similar to interfaces in C# or Java. They list off the function prototypes and variable declarations, as well as stating whether they are required or optional, but don’t actually do anything. It is up to class, structs, or enumerations that claim to conform to the protocol to actually provide the functionality.
Defining a Protocol
This is pretty easy. It is very much like defining a class in Swift, except you write protocol instead, observe:
protocol Vehicle { //Functions and properties prototypes go here. }
Then you just fill it with what you want.
[Read more…]