Start a Project

Protocols Implementation with its properties in swift

Introduction to Protocols

Protocols define a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol. In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of.

Protocol Syntax

Custom types state(Classes, Structs & Enums) can adopt a particular protocol by placing the protocol’s name after the type’s name, separated by a colon, as part of their definition. Multiple protocols can be listed, and are separated by commas:

If a class has a superclass, list the superclass name before any protocols it adopts, followed by a comma:

You might have already seen UIViewControllers implementing UICollectionViewUITableView datasource and delegate protocols.

 

Although, the best practice is to group this in a separate extension of ViewController and implement the protocols.

Adding Property Requirements

Sample Code:

Second Implementation-

Method Requirements

As mentioned earlier, protocols can have methods as well.

Sample Code:

Mutating Method Requirements

Mutating methods are methods that we use on value types like structs and enums. If you define a protocol instance method requirement that is intended to mutate instances of any type that adopts the protocol, mark the method with the mutating keyword as part of the protocol’s definition. This enables structures and enumerations to adopt the protocol and satisfy that method requirement.

Sample Code:

You can know more about protocols from here.

Thank You!!!

Exit mobile version