Swift protocol


Release date:2023-12-06 Update date:2023-12-11 Editor:admin View counts:347

Label:

Swift protocol

The protocol specifies the methods and properties necessary to implement a particular function.

Any type that meets the requirements of the protocol is called conform.

Classes, structures, or enumerated types can all follow the protocol and provide a concrete implementation to complete the methods and functions defined by the protocol.

Grammar

The syntax format of the protocol is as follows:

protocol SomeProtocol {
    // Agreement Content
}

For a class to follow a protocol, you need to add the protocol name after the type name, separated by a colon: as part of the type definition. When following multiple protocols, each protocol is separated by a comma.

struct SomeStructure: FirstProtocol, AnotherProtocol {
    // Structure Content
}

If the class has a parent class while following the protocol, the parent class name should be placed before the protocol name, separated by a comma.

class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {
    // Content of Class
}

Provisions on attributes

The protocol is used to specify specific instance or class properties, rather than specifying storage or computational properties. You must also specify whether it is read-only or read-and-write.

In protocols, variable properties are usually declared using var , followed by {set get} after type declaration to indicate that the property is readable and writable, while read-only properties are represented using {get}.

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 agreement"
    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()

print(studdet.marks)
print(studdet.result)
print(studdet.present)
print(studdet.subject)
print(studdet.stname)

The output of the above program execution is as follows:

98
true
false
Swift agreement
Swift

Yes Mutating provisions of the method

Sometimes you need to change its instance in the method.

For example, in an instance method of a value type (structure, enumeration),set the mutating keyword as a prefix to the function, written in the func previously, indicates that the value of the instance to which it belongs and its instance properties can be modified in this method.

protocol daysofaweek {
    mutating func show()
}

enum days: daysofaweek {
    case sun, mon, tue, wed, thurs, fri, sat
    mutating func show() {
        switch self {
        case .sun:
            self = .sun
            print("Sunday")
        case .mon:
            self = .mon
            print("Monday")
        case .tue:
            self = .tue
            print("Tuesday")
        case .wed:
            self = .wed
            print("Wednesday")
        case .thurs:
            self = .thurs
            print("Wednesday")
        case .fri:
            self = .fri
            print("Firday")
        case .sat:
            self = .sat
            print("Saturday")
        default:
            print("NO Such Day")
        }
    }
}

var res = days.wed
res.show()

The output of the above program execution is as follows:

Wednesday

Requirements for constructors

A protocol can require its followers to implement a specified constructor.

You can write the constructor declaration in the definition of the protocol,just as you would write a normal constructor, but you don’t need to write curly braces and constructor entities. The syntax is as follows:

protocol SomeProtocol {
   init(someParameter: Int)
}

Example

protocol tcpprotocol {
   init(aprot: Int)
}

Implementation of protocol constructor specification in class

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

class SomeClass: SomeProtocol {
   required init(someParameter: Int) {
      // Constructor implementation
   }
}

protocol tcpprotocol {
   init(aprot: Int)
}

class tcpClass: tcpprotocol {
   required init(aprot: Int) {
   }
}

Use required the modifier ensures that all subclasses that follow the protocol can also provide an explicit implementation or inheritance implementation for the constructor specification.

If a subclass overrides the specified constructor of the parent class, and the constructor follows the provisions of a protocol, then the implementation of the constructor needs to be marked at the same time required and override modifier:

protocol tcpprotocol {
    init(no1: Int)
}

class mainClass {
    var no1: Int // local variable
    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)
    }
    // Because following the protocol requires the addition of "required"; Because it inherits from the parent class, "override" needs to be added
    required override convenience init(no1: Int)  {
        self.init(no1:no1, no2:0)
    }
}
let res = mainClass(no1: 20)
let show = subClass(no1: 30, no2: 50)

print("res is: \(res.no1)")
print("res is: \(show.no1)")
print("res is: \(show.no2)")

The output of the above program execution is as follows:

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

Protocol Type

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

The protocol can be used like other common types, using scenarios:

  • As a parameter type or return value type in a function, method, or constructor

  • As a type of constant, variable, or attribute

  • As an element type in an array, dictionary, or other container

Example

protocol Generator {
    associatedtype members
    func next() -> members?
}

var items = [10,20,30].makeIterator()
while let x = items.next() {
    print(x)
}

for lists in [1,2,3].map( {i in i*5}) {
    print(lists)
}

print([100,200,300])
print([1,2,3].map({i in i*10}))

The output of the above program execution is as follows:

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

Add protocol members to the extension

We can extend existing types (classes, structures, enumerations, etc.) through extensions.

Extensions can add properties, methods, subscript scripts, protocols, and other members to existing types.

Powered by TorCMS (https://github.com/bukun/TorCMS).