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

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.

主站蜘蛛池模板: 土默特左旗| 长丰县| 甘谷县| 忻州市| 鲜城| 马关县| 浦江县| 得荣县| 珲春市| 阿坝县| 明光市| 滨州市| 泸州市| 河北省| 响水县| 江津市| 普兰县| 东乌珠穆沁旗| 仙桃市| 宣恩县| 北碚区| 阿合奇县| 榆中县| 惠水县| 从江县| 兰考县| 岐山县| 宾川县| 冷水江市| 宜都市| 永定县| 延边| 五寨县| 沧州市| 麻阳| 兴文县| 修武县| 东乌珠穆沁旗| 怀来县| 花莲市| 卫辉市|