- Swift 4 Protocol-Oriented Programming(Third Edition)
- Jon Hoffman
- 237字
- 2021-07-08 09:42:35
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.
- JBoss Weld CDI for Java Platform
- Git Version Control Cookbook
- 自己動(dòng)手實(shí)現(xiàn)Lua:虛擬機(jī)、編譯器和標(biāo)準(zhǔn)庫
- Java完全自學(xué)教程
- NLTK基礎(chǔ)教程:用NLTK和Python庫構(gòu)建機(jī)器學(xué)習(xí)應(yīng)用
- FreeSWITCH 1.6 Cookbook
- Java持續(xù)交付
- Flux Architecture
- Python完全自學(xué)教程
- 劍指MySQL:架構(gòu)、調(diào)優(yōu)與運(yùn)維
- Django 3.0入門與實(shí)踐
- Python數(shù)據(jù)可視化之美:專業(yè)圖表繪制指南(全彩)
- 人人都能開發(fā)RPA機(jī)器人:UiPath從入門到實(shí)戰(zhàn)
- Get Your Hands Dirty on Clean Architecture
- Learning D3.js 5 Mapping(Second Edition)