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

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.

主站蜘蛛池模板: 南华县| 高安市| 中宁县| 报价| 静宁县| 通山县| 太谷县| 册亨县| 会同县| 淮南市| 盐津县| 墨玉县| 泰来县| 井陉县| 安阳县| 米林县| 招远市| 汉川市| 江口县| 若尔盖县| 津南区| 张北县| 缙云县| 新泰市| 泸西县| 潮州市| 姚安县| 固原市| 哈密市| 柳河县| 安图县| 临西县| 藁城市| 射洪县| 衡山县| 荥阳市| 南开区| 洛扎县| 贵南县| 庆阳市| 古田县|