- 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.
- 從零開始構建企業級RAG系統
- Objective-C應用開發全程實錄
- PostgreSQL Cookbook
- OpenCV 3和Qt5計算機視覺應用開發
- ASP.NET Core 2 and Vue.js
- Python機器學習基礎教程
- Julia高性能科學計算(第2版)
- HTML5+CSS3 Web前端開發技術(第2版)
- Access 2010數據庫應用技術實驗指導與習題選解(第2版)
- 后臺開發:核心技術與應用實踐
- jQuery for Designers Beginner's Guide Second Edition
- Backbone.js Testing
- Kotlin語言實例精解
- Clojure編程樂趣
- 基于JavaScript的WebGIS開發