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

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.

主站蜘蛛池模板: 寿光市| 辰溪县| 丰台区| 崇明县| 乾安县| 定襄县| 白银市| 南充市| 密山市| 平乡县| 碌曲县| 马山县| 汤原县| 峨山| 武宁县| 离岛区| 海丰县| 资阳市| 哈密市| 聂拉木县| 枞阳县| 贵州省| 鄂托克前旗| 木里| 嘉荫县| 平顺县| 启东市| 高密市| 兴化市| 翁牛特旗| 齐齐哈尔市| 苏州市| 洪江市| 海伦市| 龙里县| 萨迦县| 盐津县| 卫辉市| 婺源县| 南阳市| 吉林市|