Deep analysis of protocols in Swift language _swift

Source: Internet
Author: User
Tags class definition inheritance

Protocols provide a blueprint for methods, attributes, and other required functionality. It simply describes the skeleton of the method or property, not the implementation. Method and property implementations can also be accomplished by defining classes, functions, and enumerations. The consistency of a protocol means that the method or attribute satisfies the requirements of the Protocol.

Grammar
protocols also follow the syntax of similar classes, structs, and enumerations:

Copy Code code as follows:

Protocol Someprotocol {
Protocol Definition
}



A protocol names a declaration in a class, struct, or enum type. The declaration of a single and multiple protocols is also possible. If multiple protocols stipulate, they must be separated by commas.


Copy Code code as follows:

struct Somestructure:protocol1, Protocol2 {
Structure definition
}



When a protocol is defined in a superclass, the protocol name should follow a name after the superclass.


Copy Code code as follows:

Class Someclass:somesuperclass, Protocol1, Protocol2 {
Class definition
}



requirements for properties and methods
A protocol is used to specify an instance of a particular type of property or property. It specifies only the type or instance property alone, not whether it is a stored or computed property. In addition, it is used to specify whether the property is "accessible" or "configurable."

Attribute requirements are declared by the "var" keyword as a property variable. {Get Set} declares a property to be available and configurable after using their type declarations. The fetch is referred to by their type {get} after the attribute declaration.

Copy Code code as follows:



Protocol ClassA {





var marks:int {Get Set}


var result:bool {Get}





Func attendance ()-> String


Func markssecured ()-> String





}

Protocol Classb:classa {

var present:bool {Get Set}
var subject:string {Get Set}
var stname:string {Get Set}

}

Class Classc:classb {
var marks = 96
Let result = True
var present = False
var subject = "Swift Protocols"
var stname = "Protocols"

Func attendance ()-> String {
Return "the" (Stname) has secured 99% attendance "
}

Func markssecured ()-> String {
Return "\ (Stname) has scored \ (marks)"
}
}

Let Studdet = CLASSC ()
Studdet.stname = "Swift"
Studdet.marks = 98
Studdet.markssecured ()

println (Studdet.marks)
println (Studdet.result)
println (studdet.present)
println (Studdet.subject)
println (Studdet.stname)




When we use playground to run the above program, we get the following results.

$
true
false
Swift protocols
Swift

Requirements for different deformation methods

Copy Code code as follows:



Protocol Daysofaweek {


mutating func print ()


}

Enum Days:daysofaweek {


Case Sun, Mon, Tue, Wed, Thurs, Fri, Sat


mutating func print () {


Switch Self {


Case Sun:


Self = Sun


println ("Sunday")


Case Mon:


Self = Mon


println ("Monday")


Case Tue:


Self = Tue


println ("Tuesday")


Case Wed:


Self = Wed


println ("Wednesday")


Case Mon:


Self = Thurs


println ("Thursday")


Case Tue:


Self = Fri


println ("Friday")


Case Sat:


Self = Sat


println ("Saturday")


Default


println ("NO Such Day")


}


}


}

var res = days.wed
Res.print ()




When we use playground to run the above program, we get the following results.

Wednesday

Initialization program Requirements
Swift allows the user to initialize the protocol to follow consistency similar to the normal initialization type.

Grammar

Copy Code code as follows:

Protocol Someprotocol {
Init (Someparameter:int)
}



Example


Copy Code code as follows:

Protocol Tcpprotocol {
Init (Aprot:int)
}



Protocol Initialization program Requirements class implementation


Specify or initialize the convenience to allow the user to initialize the protocol to reserve the "required" keyword to conform to its criteria.


Copy Code code as follows:

Class Someclass:someprotocol {
Required Init (someparameter:int) {
Initializer Implementation statements
}
}

Protocol Tcpprotocol {
Init (Aprot:int)
}

Class Tcpclass:tcpprotocol {
Required Init (aprot:int) {
}
}




Protocol consistency guarantees that all subclasses explicitly or implicitly implement the "required" rhetoric character.

The initialization of a subclass that overrides its superclass must be specified by the "override" modifier keyword.

Copy code code as follows:

protocol Tcpprotocol {
   init (no1:int)
}

class MainClass {
   var no1:int//local storage
   init (no1:int) {
       Self.no1 = no1//initialization
  }
}

Class Subclass:mainclass, Tcpprotocol {    var no2:int
   Init (no1:int, no2:int) {
      Self.no2 = no 2
      super.init (no1:no1)
  }
  //Requires only one Parameter for convenient method
   required override convenience init (No1:int)   {
  &nb sp;   Self.init (No1:no1, no2:0)
  }
}
Let-res = MainClass (no1:20)
Let print = Subcla SS (No1:30, no2:50)

println ("res is: \ (res.no1)")
println ("The res is: \ (print.no1)")
println ("The res is: \" (pri NT.NO2) ")




When we use playground to run the above program, we get the following results.

Res is:20
Res is:30
Res is:50

Protocol as a type
instead, the functions performed in the protocol are used as functions, classes, methods, and so on.

Protocol can be accessed as a type:

function, method, or initialization as a parameter or return type

constants, variables, or properties

arrays, dictionaries, or other containers as items

Copy Code code as follows:

Protocol Generator {
Typealias Members
Func Next ()-> members?
}

var items = [10,20,30].generate ()
While Let x = Items.next () {
println (x)
}

For lists in map ([1,2,3], {i in i*5}) {
println (lists)
}

println ([100,200,300])
println (Map ([1,2,3], {i in i*10}))




When we use playground to run the above program, we get the following results.

5
[MB]
[10, 20, 30]

Add protocol consistency and extension
existing types can conform to the new protocol through and utilize extensions. New properties, methods, and subscripts can be added to an existing type with the help of an extension.

Copy Code code as follows:



Protocol Ageclasificationprotocol {


var age:int {Get}


Func agetype ()-> String


}

Class Person {
Let firstname:string
Let lastname:string
var age:int
Init (firstname:string, lastname:string) {
Self.firstname = FirstName
Self.lastname = LastName
Self.age = 10
}
}

Extension Person:ageclasificationprotocol {


Func fullname ()-> String {


var c:string


c = FirstName + "" + LastName


Return C


}





Func agetype ()-> String {


Switch Age {


Case 0...2:


Return "Baby"


Case 2...12:


Return to "child"


Case 13...19:


Return "Teenager"


Case let x where x > 65:


Return "elderly"


Default


Return "Normal"


}


}


}





Protocol Inheritance
Swift allows the protocol to inherit the properties of its defined properties. It is similar to the inheritance of a class, but a comma-delimited enumeration selects multiple inheritance protocols.


Copy Code code as follows:



Protocol ClassA {


var no1:int {Get Set}


Func Calc (sum:int)


}

Protocol Result {
Func Print (Target:classa)
}

Class Student2:result {
Func print (Target:classa) {
Target.calc (1)
}
}

Class Classb:result {
Func print (Target:classa) {
Target.calc (5)
}
}

Class Student:classa {
var no1:int = 10

Func Calc (sum:int) {
No1-= Sum
println ("Student attempted")

If No1 <= 0 {
println ("Student is absent for exam")
}
}
}

Class Player {
var stmark:result!

Init (Stmark:result) {
Self.stmark = Stmark
}

Func print (Target:classa) {
Stmark.print (target)
}
}

var marks = Player (Stmark:student2 ())
var marksec = student ()

Marks.print (MARKSEC)
Marks.print (MARKSEC)
Marks.print (MARKSEC)
Marks.stmark = CLASSB ()
Marks.print (MARKSEC)
Marks.print (MARKSEC)
Marks.print (MARKSEC)




When we use playground to run the above program, we get the following results.

Student attempted 1 to pass
Student attempted 1 times to pass
Student attempted 1 times to pass
Student Attempted 5
Student attempted 5 times to pass Student are absent for exam Student
attempted 5 Tim Es to pass
Student are absent for exam

Only class protocols
when the protocol is defined and the user wants to define the protocol with the class it should be added by defining the class first followed by the inheritance list of the protocol.

Copy Code code as follows:

protocol Tcpprotocol {
   init (no1:int)
}

class MainClass {
   var no1:int//local storage
   init (no1:int) {
       Self.no1 = no1//initialization
  }
}

Class Subclass:mainclass, Tcpprotocol {    var no2:int
   Init (no1:int, no2:int) {
      Self.no2 = no 2
      super.init (no1:no1)
  }
  //Requires only one Parameter for convenient method
   required override convenience init (No1:int)   {
  &nb sp;   Self.init (No1:no1, no2:0)
  }
}

Let res = MainClass (no1:20)
Let print = S Ubclass (no1:30, no2:50)

println ("res is: \ (res.no1)")
println ("The res is: \ (print.no1)")
println ("The Res is: \ (Print.no2) ")




When we use playground to run the above program, we get the following results.

Res is:20
Res is:30
Res is:50

Protocol Combination
Swift allows multiple protocols to be used once with the help of the Protocol portfolio.

Grammar

Copy Code code as follows:

Protocol<someprotocol, anotherprotocol>



Example


Copy Code code as follows:

Protocol Stname {
var name:string {Get}
}

Protocol Stage {
var age:int {Get}
}

struct Person:stname, stage {
var name:string
var age:int
}

Func print (Celebrator:protocol<stname, stage>) {
println ("\ (celebrator.name) is \ (celebrator.age) years old")
}

Let Studname = person (name: "Priya", age:21)
Print (Studname)

Let stud = person (name: "Rehan", age:29)
Print (stud)

Let student = person (name: "Roshan", age:19)
Print (student)




When we use playground to run the above program, we get the following results.

Priya is years an old
Rehan is * years old
Roshan am years old

Check Protocol consistency
protocol Consistency is an operator test that is and as similar to type conversions.

If an instance conforms to the protocol criteria, the IS operator returns TRUE if the failure returns false.

As? The version is a downward transition operator that returns an optional value for the type of the protocol, and if the value is nil, the instance does not conform to the protocol.

The as version is the downward transition operator, forcing a downward transition of the protocol type and triggering a run-time error if the downward transition does not succeed.

Copy Code code as follows:



Import Foundation

@objc protocol Rectangle {
var area:double {Get}
}

@objc class Circle:rectangle {
Let pi = 3.1415927
var radius:double
var area:double {return pi * radius * radius}
Init (radius:double) {Self.radius = radius}
}

@objc class Result:rectangle {
var area:double
Init (area:double) {Self.area = area}
}


Class Sides {
var rectsides:int
Init (rectsides:int) {self.rectsides = rectsides}
}

Let objects: [Anyobject] = [Circle (radius:2.0), result (area:198), Sides (Rectsides:4)]

For object in Objects {
If let Objectwitharea = object as? Rectangle {
println ("area is \ (Objectwitharea.area)")
} else {
println ("Rectangle area isn't defined")
}
}




When we use playground to run the above program, we get the following results.

The area is 12.5663708 the area is 198.0 Rectangle the is isn't
defined

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.