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

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.

主站蜘蛛池模板: 金阳县| 西丰县| 高台县| 鄢陵县| 泾川县| 湖南省| 东平县| 抚松县| 孝昌县| 霍邱县| 沧州市| 新平| 岑溪市| 庆元县| 棋牌| 芒康县| 枣庄市| 彩票| 晋宁县| 延寿县| 晋宁县| 武安市| 维西| 津南区| 武夷山市| 临夏县| 长武县| 吉林省| 云梦县| 南郑县| 杭锦旗| 万安县| 桑植县| 广安市| 华阴市| 南平市| 清远市| 南充市| 海南省| 瑞金市| 齐齐哈尔市|