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

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.

主站蜘蛛池模板: 泸溪县| 和硕县| 和田市| 双江| 镇江市| 柘城县| 昌黎县| 赤壁市| 达日县| 晋江市| 桃园县| 固镇县| 什邡市| 漳平市| 孟连| 成武县| 隆回县| 崇义县| 边坝县| 图们市| 鹤庆县| 通城县| 鄱阳县| 镇江市| 武宁县| 宜黄县| 乐安县| 泽普县| 青田县| 大关县| 铁力市| 长阳| 双城市| 定陶县| 靖边县| 陇西县| 皋兰县| 乌什县| 四平市| 苏尼特左旗| 荆州市|