官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 浠水县| 清涧县| 忻州市| 鄂州市| 麻栗坡县| 岚皋县| 从化市| 余干县| 陇西县| 横峰县| 宜宾县| 七台河市| 肃北| 聊城市| 习水县| 溧阳市| 砚山县| 北票市| 鹤壁市| 南溪县| 双流县| 峨眉山市| 合水县| 顺平县| 阳高县| 寿宁县| 芜湖县| 合江县| 淅川县| 甘谷县| 武安市| 家居| 吉木萨尔县| 宜黄县| 云林县| 定兴县| 聂拉木县| 柞水县| 阿图什市| 邢台县| 荆门市|