Using protocols as a type

Even though no functionality is implemented in a protocol, they are still considered a full-fledged type in the Swift programming language, and can mostly be used like any other type. What this means is that we can use protocols as parameters or return types for a function. We can also use them as the type for variables, constants, and collections. Let's look at some examples of this. For these next few examples, we will use the following Person protocol:

protocol Person { 
  var firstName: String {get set} 
  var lastName: String {get set}  
  var birthDate: Date {get set}  
  var profession: String {get} 
  init (firstName: String, lastName: String, birthDate: Date) 
} 

In this Person protocol, we define four properties and one initializer.

For this first example, we will show how to use a protocol as a parameter and return type for a function, method, or initializer. Within the function itself, we also use the Person as the type for a variable:

func updatePerson(person: Person) -> Person {  
  var newPerson: Person 
  // Code to update person goes here  
  return newPerson 
} 

We can also use protocols as the type to store in a collection, as shown in the next example:

var personArray = [Person]() 
var personDict = [String: Person]() 

We can use the instance of any type that conforms to our protocol anywhere that the protocol type is required. Let's assume that we have two types named SwiftProgrammer and FootballPlayer that conform to the Person protocol. We can then use them as shown in this next example:

var myPerson: Person 
 
myPerson = SwiftProgrammer(firstName: "Jon", lastName: "Hoffman", birthDate: birthDateProgrammer) 
myPerson = FootballPlayer(firstName: "Dan", lastName: "Marino", birthdate: birthDatePlayer) 

As we saw earlier, we can use the Person protocol as the type for an array, which means that we can populate the array with instances of any type that conforms to the Person protocol. The following is an example of this (note that the bDateProgrammer and bDatePlayer variables are instances of the Date type that would represent the birth date of the individual):

var programmer = SwiftProgrammer(firstName: "Jon", lastName: "Hoffman",
birthDate: bDateProgrammer) var player = FootballPlayer(firstName: "Dan", lastName: "Marino",
birthDate: bDatePlayer) var people: [Person] = [] people.append(programmer) people.append(player)

What we are seeing in these last couple of examples is a form of polymorphism. To use protocols to their fullest potential, we need to understand what polymorphism is.