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

Protocol inheritance

Protocols can inherit requirements from one or more additional protocols and then add additional requirements. The following code shows the syntax for protocol inheritance:

protocol ProtocolThree: ProtocolOne, ProtocolTwo { 
  // Add requirements here 
} 

The syntax for protocol inheritance is very similar to class inheritance in Swift, except that we are able to inherit from more than one protocol. Let's see how protocol inheritance works. We will use the FullName protocol that we defined earlier and create a new protocol named Person:

protocol Person: FullName {  
  var age: Int {get set} 
} 

Now, when we create a type that conforms to the Person protocol, we must implement the requirements defined in the Person protocol, as well as the requirements defined in the FullName protocol. As an example, we could define a Student structure that conforms to the Person protocol, as shown in the following code:

struct Student: Person {  
  var firstName = ""  
  var lastName = ""  
  var age = 0 
 
  func getFullName() -> String {  
    return "\(firstName) \(lastName)"
  } 
} 

Note that in the Student structure, we implemented the requirements defined in both the FullName and Person protocols. However, the only protocol specified in the structure definition was the Person protocol. We only needed to list the Person protocol because it inherited all the requirements from the FullName protocol.

Now let's look at a very important concept in the protocol-oriented programming paradigm: Protocol composition.

主站蜘蛛池模板: 时尚| 乌兰浩特市| 手游| 城步| 大石桥市| 靖宇县| 化隆| 五莲县| 荃湾区| 许昌县| 沧源| 绍兴市| 台前县| 宜阳县| 格尔木市| 长宁区| 双流县| 吐鲁番市| 临朐县| 扎鲁特旗| 松滋市| 江孜县| 博湖县| 德格县| 乐业县| 玛纳斯县| 平武县| 呼玛县| 军事| 威信县| 镇雄县| 太和县| 体育| 潮州市| 宜良县| 商水县| 磴口县| 马龙县| 榆社县| 神农架林区| 永春县|