Swift-11-Protocol (protocols)

Source: Internet
Author: User
Tags instance method

A protocol defines a blueprint that specifies the methods and properties necessary to implement a particular work or function. Classes, structs, or enumeration types can follow the protocol and provide specific implementations to complete the methods and functions of the Protocol definition. Any type that satisfies the requirements of the Protocol is referred to as following the conform protocol.

In addition to conforming to the type of protocol that must be implemented, the protocol can be extended to implement some special provisions or additional functions that will benefit the type of compliance.

Formula for the protocol:

Protocol Someprotocol {//protocol contents}

To make a class conform to a protocol, you need to add a protocol name after the type name, separated by a colon: as part of the type definition, and separated by commas when you follow multiple protocols.

struct somestructure:firstprotocol,anotherprotocol{    //structure contents}

If a class has a parent class that adheres to the protocol, the parent class name should be placed before the protocol name, separated by commas.

Class someclass:somesuperclass,firstprotocol,anotherprotocol{  //content  }

The provisions of attributes

A protocol can stipulate that its followers provide instance properties (instance property) or class properties (Type property) of a specific name and type, rather than specifying a stored-type attribute (stored property) or a computed type property (calculate property), and must also indicate whether it is readable 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 (gettable), then the property can be read-only, and can be writable if your code requires it.

In the protocol, the variable property is usually declared with Var, with the type declaration followed by {set Get} to indicate that the property is readable and writable, and the read-only attribute is represented by {get}.

Protocol someprotocol{  var mustbesettable:int {get set}//readable writable  var donenotneedtobesettable:int{get}    //Read-only }

When you define class properties (Type property) in the protocol, always use the static keyword as the prefix. You can use the class or the static keyword to declare class properties when the protocol's subject is a class.

Protocol anotherprotocol{  static var sometypeproperty:int{get set}  }

Here's an example.

Protocol fullynamed{  var fullname:string {get}}

In addition to requiring the compliance of the Agreement to provide a full-name attribute, the FULLYNAMED protocol has no specific requirement for the type of compliance of the Protocol. This protocol indicates that any type that follows the FULLYNAMED protocol has a readable instance property of type string fullyname.

A simple struct that follows the Fullnamed protocol person:fullynamed{  var fullname:string  }let john = person (fullName: "John Appleseed ")

This example defines a struct called person, which is used to represent a name, as can be seen from the first line of code, which follows the fullynamed protocol.

Each instance of the person struct has a stored-type property fullname that is a string. This satisfies the requirements of the Fullynamed protocol, which means that the person structure is fully compliant with the protocol. ---If the protocol requirements are not fully met, an error will be encountered at compile time

Class starship:fullynamed{  var prefix:string?  var name:string  Init (name:string, prefix:string = nil) {        self.name = name        self.prefix = prefix          }        var fullname:string{      return (prefix! = nil? prefix! + "": "") +name          }  }var NCC = Starship (Name: "Enterprise", Prefix: "USS")

The FullName property is implemented as a readable computed type property.

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, in the same way as normal method definitions. However, parameter defaults are not supported in the method definition of the protocol.

As stated in the provisions of the attribute, the static keyword is always used as the prefix when defining class methods in the protocol. When the protocol's followers are classes, you can define class methods using class or static in the implementation of the classes:

Protocol someprotocol{    static Func Sometypemethod ()}

The following example defines a protocol that contains an instance method:

Protocol randomnumbergenerator{   func random () Double}

Provisions of the Mutating method

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

------use the class to implement the Mutating method in the protocol, you do not have to write the mutating keyword; When you enumerate the mutating methods in the protocol using structs, you must write the mutating keyword.

Rules for constructors

A protocol can require its followers to implement a specific constructor, which can be written in the definition of the protocol, but without the need to write curly braces and constructor entities.

Protocol someprotocol{    Init (someparameter:int)}

Implementation of protocol constructors in classes

You can implement a constructor in a class that follows the protocol and specify it as the specified constructor for the class (designated initializer) or a convenience constructor (convenience initializer). In this case, you must label the constructor "required "Modifier.

  

Class someclass:someprotocol{    required init (someparameter:int) {   //constructor implementation        }}

Using the required modifier guarantees that all subclasses that follow the protocol can also provide an explicit implementation or inheritance implementation for the constructor's requirements.

If the class has already been marked as final, you do not need to use the required modifier in the implementation of the Protocol builder. Because the final class cannot have subclasses.

If a subclass overrides the specified constructor of the parent class, and the constructor follows the provisions of a protocol, the implementation of the constructor needs to be identified by the colleague required and the override modifier:

  

Protocol someprotocol{   Init ()  }class somesuperclass{   init () {    //constructor implementation   }}class Somesubclass: somesuperclass,someprotocol{   //Because following the agreement, you need to add required, because inheriting from the parent class, you need to add the override  required override init () {     }       }

Can fail the constructor

You can add a failed constructor to the protocol protocols to make the type that adheres to the protocol must implement the failed constructor.

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 the type that adheres to 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 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:
1. As a function, a method, or a parameter type in a constructor or a return value type;

2, as the type of constant, variable or attribute;

3. As an element type in an array, dictionary, or other container.

Attention:

A protocol is a type, so the name of the protocol type should be the same as other types (Int, double,string), and camel-style notation that begins with uppercase letters.

  

Swift-11-Protocol (protocols)

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.