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

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.

主站蜘蛛池模板: 大埔区| 措美县| 城口县| 昌宁县| 辽宁省| 怀安县| 大渡口区| 广丰县| 桑日县| 阿鲁科尔沁旗| 双辽市| 招远市| 韶关市| 曲麻莱县| 衢州市| 浠水县| 南投县| 辉南县| 射阳县| 卢龙县| 江城| 深水埗区| 繁峙县| 扎赉特旗| 兴宁市| 义马市| 应城市| 汶上县| 平安县| 阿拉善右旗| 定兴县| 平罗县| 广州市| 乌拉特中旗| 阿拉善盟| 宣武区| 淳化县| 大渡口区| 延津县| 正镶白旗| 阿图什市|