In depth analysis of the protocols in the Swift language

  • 2020-05-14 05:00:08
  • OfStack

The protocol provides a blueprint for methods, properties, and other required functionality. It simply describes the skeleton of a method or property, not the implementation. Method and property implementations can also be done by defining classes, functions, and enums. Protocol 1 specificity refers to a method or attribute that meets protocol requirements.

grammar
The protocol also follows the syntax of similar classes, constructs, and enums:


protocol SomeProtocol {
    // protocol definition
}

Protocol in class, structure or enumeration type naming declarations. Single and multiple protocol declarations are also possible. If multiple protocols specify, they must be separated by commas.

struct SomeStructure: Protocol1, Protocol2 {
    // structure definition
}

When a protocol is defined in a superclass, the protocol name follows the name of the superclass.

class SomeClass: SomeSuperclass, Protocol1, Protocol2 {
    // class definition
}

Property and method requirements
The protocol is used to specify a property of a particular type or an instance of an attribute. It specifies only the type or instance property individually rather than whether it is a storage or compute property. In addition, it is used to specify whether the property is "retrievable" or "settable".

Properties are required to be declared as property variables by the "var" keyword. {get set} declaration properties are available and settable after they are typed. Retrievable is referred to by their type {get} after a property declaration.


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 run the above program using playground, we get the following results.


98
true
false
Swift Protocols
Swift

Different deformation method requirements


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 run the above program using playground, we get the following results.


Wednesday

Initializer requirements
Swift allows user initialization protocols to follow a 1 tropism similar to normal initialization types.

grammar


protocol SomeProtocol {
   init(someParameter: Int)
}

The sample

protocol tcpprotocol {
   init(aprot: Int)
}

The protocol initializer requires class implementation
Specifying or initializing convenience allows the user to initialize the protocol to reserve the "required" keyword to meet its criteria.

class SomeClass: SomeProtocol {
   required init(someParameter: Int) {
      // initializer implementation statements
   }
} protocol tcpprotocol {
   init(aprot: Int)
} class tcpClass: tcpprotocol {
   required init(aprot: Int) {
   }
}

Protocol 1 specificity guarantees that all subclasses explicitly or inherit the implementation of the "required" rhetoric.

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


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 = no2
      super.init(no1:no1)
   }
   // Requires only one parameter for convenient method
   required override convenience init(no1: Int)  {
      self.init(no1:no1, no2:0)
   }
}
let res = mainClass(no1: 20)
let print = subClass(no1: 30, no2: 50) println("res is: \(res.no1)")
println("res is: \(print.no1)")
println("res is: \(print.no2)")

When we run the above program using playground, 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 types such as functions, classes, methods, etc.

The protocol can be accessed as a type:

A function, method, or initialization is one parameter or return type

A constant, variable, or property

An array, dictionary, or other container as an item


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 run the above program using playground, we get the following results.


10
20
30
5
10
15
[100, 200, 300]
[10, 20, 30]

Add protocol 1 conformance and extensions
Existing types can be extended to conform to new protocols. New properties, methods, and subscripts can be added to existing types with the help of extensions.


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 "Child"
      case 13...19:
         return "Teenager"
      case let x where x > 65:
         return "Elderly"
      default:
         return "Normal"
      }
   }
}

Agreement inheritance
Swift allows the protocol to inherit the properties of the properties it defines. It is similar to inheritance of a class, but with a comma separated list of multiple inheritance protocols to select.

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 \(sum) times to pass")
     
      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 run the above program using playground, we get the following results.


Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 5 times to pass
Student attempted 5 times to pass
Student is absent for exam
Student attempted 5 times to pass
Student is absent for exam

Class only protocol
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 protocol's inheritance list.


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 = no2
      super.init(no1:no1)
   }
   // Requires only one parameter for convenient method
   required override convenience init(no1: Int)  {
      self.init(no1:no1, no2:0)
   }
} let res = mainClass(no1: 20)
let print = subClass(no1: 30, no2: 50) println("res is: \(res.no1)")
println("res is: \(print.no1)")
println("res is: \(print.no2)")

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


res is: 20
res is: 30
res is: 50

Protocol combinations
Swift allows multiple protocols to be called once with the help of a protocol combination.

grammar


protocol<SomeProtocol, AnotherProtocol>

The sample

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 run the above program using playground, we get the following results.


Priya is 21 years old
Rehan is 29 years old
Roshan is 19 years old

Check protocol 1 conformance
Protocol 1 specificity is is and as similar to operator tests for type conversion.

The is operator returns false if one instance meets the protocol standard, or true if it fails.

as & # 63; The version is a downward transition operator that returns an optional value of the type of protocol, and if the value is nil, the instance does not conform to the protocol.

The as version is a downshift operator that forces a downshift protocol type and triggers a runtime error if the downshift does not succeed.


 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 is not defined")
   }
}

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


Area is 12.5663708
Area is 198.0
Rectangle area is not defined


Related articles: