Protocol Property Protocol
We can define properties in the protocol, and the following code is wrong because the read-only attribute is defined in the protocol, but it attempts to modify its value:
Protocol Fullynamed {varfullname:string {Get}}structperson:fullynamed{varFullname:string} LetJohn = person (fullName:"Why") John.fullname ="Why" //error!
Protocol synthesis
A protocol can be combined in such a format by multiple protocols protocol<SomeProtocol, AnotherProtocol>
, called Protocol Synthesis (Protocol composition).
Protocol Named {varname:string {Get}}protocol aged {varAge:int {Get}}structPerson:named, aged {varName:stringvarAge:int}func Wishhappybirthday (celebrator:protocol<named, aged>) {println ("Happy birthday \ (celebrator.name)-you ' re \ (celebrator.age)!")} LetBirthdayperson = person (name:"Malcolm", Age: +) Wishhappybirthday (Birthdayperson)
Protocol Combat
Let's design a counter to practice the protocol-related content.
First define a protocol, counterdatasource
This protocol provides an increment value, that is, the number of increments that the counter counts each time. This value can be a fixed value, such as increment one at a time, or it can be a method that returns different increment values depending on the situation. So our definition is as follows:
@objc protocol Counterdatasource {optional func incrementforcount< Span class= "Hljs-params" style= "Box-sizing:border-box;" > (Count:int) -> Int optional var fixedincrement : Int {get}}
@objc
Indicates that the protocol is optional and can also be used to represent code exposed to OBJECTIVE-C, only valid for the class.
Next we define a counter, which has aCounterDataSource
Type of data source. It's kind of likeUITableViewDataSource
The sense that we are going through this protocol to get this count to increase the step size. IfdataSource
Realized theincrementForCount
method, the step is obtained by this method, otherwise see if the step can be obtained by a fixed value:
@objc class Counter { varCount =0 var DataSource: Counterdatasource? Func increment () {if LetAmount = DataSource?. Incrementforcount? (count) {count + = amount}Else if LetAmount = DataSource?. Fixedincrement? {count + = amount}}}
You can count with a fixed value first:
classThreesource:counterdatasource { LetFixedincrement =3}varCounter = Counter () Counter.datasource = Threesource () for_inch 1... 4{counter.increment () println (Counter.count)}//3//6//9//
You can also use methods to count:
classTowardszerosource:counterdatasource {func incrementforcount (count:int), Int {ifCount = =0{return 0}Else ifCount <0{return 1}Else{return-1}}}counter.count =-4Counter.datasource = Towardszerosource () for_inch 1... 5{counter.increment () println (Counter.count)}//-3//-2//-1//0//0
Recent time is limited, simply read the official documentation. Later, I met a supplementary.
References
[Swift] DAY13: protocol