- Swift 4 Protocol-Oriented Programming(Third Edition)
- Jon Hoffman
- 201字
- 2021-07-08 09:42:35
Defining a protocol
The syntax we use to define a protocol is very similar to the syntax used to define a class, structure, or enumeration. The following example shows the syntax used to define a protocol:
Protocol MyProtocol { //protocol definition here }
To define the protocol, we use the protocol keyword followed by the name of the protocol. We then put the requirements, which our protocol defines, between curly brackets. Custom types can state that they conform to a particular protocol by placing the name of the protocol after the type's name, separated by a colon. The following example shows how we would define that a structure conforms to a protocol:
struct MyStruct: MyProtocol { //structure implementation here }
A type can also conform to multiple protocols. We list the multiple protocols that the type conforms to by separating them with commas:
struct MyStruct: MyProtocol, AnotherProtocol, ThirdProtocol { // Structure implementation here }
Having a type conform to multiple protocols is a very important concept within protocol- oriented programming, as we will see later in the chapter and throughout this book. This concept is known as protocol composition.
Now let's see how we would add property requirements to our protocol.
- 騰訊iOS測試實(shí)踐
- Android 9 Development Cookbook(Third Edition)
- 基于差分進(jìn)化的優(yōu)化方法及應(yīng)用
- Java虛擬機(jī)字節(jié)碼:從入門到實(shí)戰(zhàn)
- Hadoop+Spark大數(shù)據(jù)分析實(shí)戰(zhàn)
- 高級C/C++編譯技術(shù)(典藏版)
- Java Fundamentals
- Essential C++(中文版)
- TypeScript圖形渲染實(shí)戰(zhàn):2D架構(gòu)設(shè)計與實(shí)現(xiàn)
- 大學(xué)計算機(jī)應(yīng)用基礎(chǔ)(Windows 7+Office 2010)(IC3)
- 編程的原則:改善代碼質(zhì)量的101個方法
- 少年小魚的魔法之旅:神奇的Python
- Building E-Commerce Solutions with WooCommerce(Second Edition)
- Oracle API Management 12c Implementation
- Kotlin核心編程