Learning Swift--agreement (on)

Source: Internet
Author: User
Tags instance method

Protocol (UP)

The agreement is a very important part of Swift, which specifies the methods and properties necessary to implement a particular work or function. class, struct, or enum type can follow the and provide specific implementations to complete the protocol definition methods and functions. Any type that satisfies the requirements of the Protocol is called 遵循 this protocol.

Protocol Someprotocol {    //protocol content}struct Somestruct:someprotocol {//    struct and enumeration can follow the protocol, the wording ": protocol name" is the number of protocol names separated by commas} Class SomeClass {    }class subclass:someclass, Someprotocol {    ///If a class inherits a parent class and follows a protocol notation with ": Parent class name, protocol", note that the parent class name is before the protocol After

The provisions of attributes

The agreement can 遵循者 specify whether it provides a specific name and type 实例属性 , or whether it 类属性 is specified or not 存储型属性 计算型属性 . It must also indicate whether it is read-only or readable and writable.

This property cannot be a constant or read-only computed property if the protocol specifies that the attribute is readable and writable. If the protocol only requires that the property be read-only, that property can be read-only, and can be writable if your code requires it.

A property is usually declared with Var in the protocol, followed by a type declaration { set get } to indicate that the property is readable and writable, and the read-only attribute is used { get } to represent it.

when defining class properties in the protocol, always use the static keyword as the prefix. when the protocol's subject is a class, you can class declare the class property using the OR keyword, but in the definition of the static protocol, you still use the keyword static .

Protocol Someprotocol {    var mustbesettable:int {Get Set}         //Readable writable property    var doesnotneedtobesettable:int {get }    //Read-only property}protocol Anotherprotocol {    static var sometypeproperty:int {Get Set}    //Type Property}

Here is a follow FullyNamedThe simple structure of the protocol.
Protocol fullynamed {    var fullname:string {get}}struct person:fullynamed {     //followed fullynamed protocol    var Fulln Ame:string        //Follow the agreement, you must declare the properties stipulated in the agreement fullname}let Alex = person (fullname: "Alex")

The following is a more complex class
Protocol fullynamed {    var fullname:string {get}}class starship:fullynamed {    var fullname:string {      //ful Lynamed Property declaration for a read-only computed property        return (prefix! = nil? prefix! + "": "") + name    }        var prefix:string?    var name:string    Init (name:string, prefix:string = nil) {        self.name = name        self.prefix = prefix    }}let ncc1701 = Starship (Name: "Enterprise", Prefix: "USS") Ncc1701.fullname    //USS Enterprise

provisions of the method

A protocol can require its followers to implement certain specified instance methods or class methods. These methods, as part of the protocol, are placed in the definition of the protocol as normal methods, but no curly braces and method bodies are required. methods with variable parameters can be defined in the protocol , and the normal method is defined in the same way. However, parameter defaults are not supported in the method definition of the protocol .

As stated in the provisions of the attribute, the keyword is always used static as the prefix when defining the class method in the protocol. When the protocol's followers are classes, you can use or implement the class method in the implementation of the class, class static but declare the class method in the protocol and still use the static keyword.

Protocol Someprotocol {    static func Sometpyemethod ()}protocol randomnumbergenerator {    func random () Double}

Example:

Protocol RandomNumberGenerator {    func random (), Double}class linearcongruentialgenerator: RandomNumberGenerator {    var lastrandom = 42.0 let    m = 139968.0 let    a = 3877.0 let    c = 29573.0    func ran Dom (), Double {       //Declaration protocol method        Lastrandom = (Lastrandom * A + c)% m        return lastrandom/m    }}let Generato R = Linearcongruentialgenerator () print ("Here ' s a random number: \ (Generator.random ())")//Print out: "Here's a random number:0 .37464991998171 "Print (" another one: \ (Generator.random ()) ")//Print out:" Another one:0.729023776863283 "

provisions of the mutating method

Sometimes it is necessary to change its instance in a method. For example, in an instance method of a value type (struct, enum), the keyword is prefixed to a mutating function, written before, to indicate that the value of the func instance and its instance properties that it belongs to can be modified in the method.

Note: When using a class to implement a method in a protocol, you do mutating not have to write a keyword mutating ; When you enumerate the methods in the protocol by using structs, you mutating must write the keywords mutating .

Protocol Someprotocol {    mutating func mutatingfunc ()}struct Somestruct:someprotocol {    var number = 2    mutating func Mutatingfunc () {Number        =    }}class someclass:someprotocol {    var number = 1    func Mutati Ngfunc () {number = +}    }

Example:

Protocol Togglable {    mutating func toggle ()}enum onoffswitch:togglable {case    Off, on    mutating func Toggl E () {        switch self}        : Self            =. Off case        off: self            =. On        }    }}var lightSwitch = OnOffSwitch.OnlightSwitch.toggle ()            //LightSwitch now off

rules for constructors

A protocol can require its followers to implement the specified constructor. You can write the constructor's declaration in the definition of the protocol as you would write a normal constructor, but you do not need to write the curly braces and the constructor's entities:

Protocol someprotocol{    Init (someparameter:int)}

implementation of the Protocol constructor in the class

You can implement a constructor in a class that follows the protocol and specify it as the specified constructor for the class or a convenience constructor. In both cases, you must label the constructor implementation with the "required" modifier.

Note: If the class is already marked final , you do not need to use modifiers in the implementation of the Protocol constructor required . Because the final class cannot have subclasses

Class Someclass:someprotocol {    required init (someparameter:int) {     //must be added required keyword        //construction process    }}final Class Finalclass:someprotocol {    init (someparameter:int) {              ///Because it is marked as final, you can not add the required keyword        //construction process c14/>}}

Protocol someprotocol{    Init ()}class somesuperclass{    init () {            }}class somesubclass:somesuperclass, Someprotocol {    //because following the agreement, you need to add "required" because it inherits from the parent class and needs to add "override"    required override init () {            }}

rules for failed constructors

It is possible to Protocols implement the failed constructor by adding a failed constructor to the protocol so that the type that follows the protocol must be implemented.

If a failed constructor is defined in the protocol, a failed constructor or a non-failed constructor with the same name as the same parameter must be added in compliance with the Xu type of the protocol. If a non-failed constructor is defined in the protocol, a non-failed constructor with the same name or an implicitly resolved type must be added in the type that adheres to the Protocol ( init! ).

Protocol someprotocol{    init? ()    Init (someparameter:int)}class someclass:someprotocol{    required init () {   //or init? ()            }    Required init! (Someparameter:int) {    //or init (Someparameter:int)            }}

protocol Type

Although the protocol itself does not implement any functionality, the protocol can be used as a type.

Protocols can be used just like other normal types, using scenarios:

    • As a parameter type or return value type in a function, method, or constructor
    • As the type of a constant, variable, or property
    • As an element type in an array, dictionary, or other container

Note: The protocol is a type, so the name of the protocol type should be the same as other types (int,double,string), with camel-like notation beginning with uppercase letters.

Protocol RandomNumberGenerator {    func random (), Double}class linearcongruentialgenerator: RandomNumberGenerator {    var lastrandom = 42.0 let    m = 139968.0 let    a = 3877.0 let    c = 29573.0    func ran Dom (), Double {        lastrandom = ((Lastrandom * a + c)% m)        return lastrandom/m    }}class Dice {let    side S:int    Let Generator:randomnumbergenerator     //attribute types can be used with    the protocol type init (Sides:int, Generator: RandomNumberGenerator)    The type of the {//parameter can also be a protocol type        self.sides = sides        self.generator = Generator    }    Func roll (), int {        return int (generator.random () * Double (sides)) + 1    }}var d6 = Dice (sides:6, Generator: Linearcongruentialgenerator ()) D6.roll ()   //3d6.roll ()   //5d6.roll ()   //4

delegate (proxy) mode

The

delegate is a design pattern, It allows the class or struct to delegate some of the functions that need them to be (delegated) To other instances of the type. The implementation of the delegate pattern is simple: Define the protocol to encapsulate the functions and methods that need to be delegated, so that their followers have these delegated functions and methods . The delegate pattern can be used to respond to a specific action or to receive data from an external data source without needing to know the type information of the external data source.

Protocol RandomNumberGenerator {func random (), Double}class linearcongruentialgenerator:randomnumbergenerator { var lastrandom = 42.0 Let M = 139968.0 let a = 3877.0 let C = 29573.0 func random () Double {L Astrandom = ((Lastrandom * a + c)% m) return lastrandom/m}}class Dice {Let sides:int let generator: RandomNumberGenerator Init (Sides:int, generator:randomnumbergenerator) {self.sides = sides Self.generat or = generator} func roll (), int {return int (generator.random () * Double (sides)) + 1}}protocol Dic EGame {var dice:dice {get} func play ()}protocol dicegamedelegate {func gamedidstart (game:dicegame) func Game (Game:dicegame, Didstartnewturnwithdiceroll diceroll:int) func gamedidend (game:dicegame)}class SnakesAndLadders    : dicegame {//protocol only requires dice to be read-only, so dice is declared as a constant property. Let Dice:dice = Dice (Sides:6, Generator:linearcongruentialgenerator ()) Let Finalsquare =var square = 0 var board: [Int] init () {board = Array (Count:finalsquare, repeatedvalue:0) boa RD[03] = +08; BOARD[06] = +11; BOARD[09] = +09; BOARD[10] = +02 board[14] =-10; BOARD[19] =-11; BOARD[22] =-02;    BOARD[24] = -08} var delegate:dicegamedelegate? Func Play () {square = 0 delegate?. Gamedidstart (self) gameloop:while square! = finalsquare {Let Diceroll = Dice.roll () Delegat E?.                Game (self, didstartnewturnwithdiceroll:diceroll) switch Square + diceroll {case Finalsquare:            Break Gameloop case Let Newsquare where Newsquare > Finalsquare:continue gameloop        Default:square + = Diceroll square + Board[square]}} Delegate?. Gamedidend (self)}}class dicegametracker:dicegamedelegate {var numberofturns = 0 Func gamedidstart (game:dicega Me) {//The game starts doing some thinkingDo things} func game (Game:dicegame, Didstartnewturnwithdiceroll diceroll:int) {//game in progress Numberofturns + = 1 Print ("Rolled a \ (Diceroll)")} func Gamedidend (game:dicegame) {//End of game print ("The Games L Asted for \ (numberofturns) turns ")}}let tracker = Dicegametracker () Let game = Snakesandladders () game.delegate = Tracke Rgame.play ()//rolled a 3//rolled a 5//rolled a 4//rolled a 5//"The game lasted for 4 turns"

Learning Swift--agreement (on)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.