Swift Protocols

In swift, Protocols are used to define a skeleton of classes, structures, methods, types and that would require other types to implement defined classesmethods, properties. The defined protocol adopted by other classes or methods to provide an actual implementation of defined properties or methods.

 

If we work on other programming languages the term protocol is similar to interfaces in Java and C#. Protocols only responsible for the signature of methods and functions.

 

Generally, in swift we use a protocol keyword to define protocols in our applications.

Swift Protocol Syntax

The syntax of protocol is very similar to classstructure, and enumeration but there is only a difference is protocol keyword and implementation type section.

 

Following is the syntax of defining a protocol in a swift programming language.

 

protocol ProtocolName {

// Structure Body Here

}

We can adopt the defined protocol in structure or a class by placing a protocol name after the type name which is separated by a colon (:) during its declaration. In case if we have multiple protocols to adopt those are separated by commas (,) like as shown below

 

struct fullnameStructure: FirstNameProtocol, lastNameProtocol {

// Structure Body Here

}

In case class have a superclass, we need to list the class name first then we need to add the protocol names which we are going to adopt like as shown below 

 

class fullnameClass: ParentClass, FirstNameProtocol, lastNameProtocol {

// Class Body Here

}

Swift Protocol Properties and Methods Requirements

In swift protocol, we can define the methods and properties rather than their implementation. In protocol, we don’t need to specify whether the property is stored property or computed property it required only property name and type. We can also specify whether the property is gettable or gettable and settable.

 

In protocol always we need to define properties as a variable with var keyword. In case if we need a define a property with gettable and settable properties then we need to declare it like { get set } after its type declaration same way only gettable property will define like { get }.

 

If we want to define methods in protocol those methods definition will be same normal instance and type methods but without curly braches and method body. 

 

Following is the example of defining properties and methods in protocols and adopt those protocols to implement defined properties and methods in another class.

 

protocol name {

var fullname:String {get set}

var Age:Int {get set}

func detail()-> String

}

protocol stuname : name {

var marks:Int {get set}

}

class school: stuname,name {

var fullname: String = "Suresh"

var Age: Int = 23

var marks: Int = 99

func detail() -> String {

return"Student Name: \(fullname), Age: \(Age), Total Marks: \(marks)"

}

}

let sch =  school()

sch.fullname = "Suresh Dasari"

sch.Age = 30

sch.marks = 520

print(sch.detail())

If you observe above example we defined a protocols name, stuname with required propertiesmethods and we adopted those protocols by a class school to implement a protocol functions and properties.

 

When we run the above example in swift playground we will get a result like as shown below

 

Student Name: Suresh Dasari, Age: 30, Total Marks: 520

This is how we can define properties and methods in protocols and adopt those protocols to implement defined methods and properties of protocols in class or structure based on our requirements.

Swift Protocol Mutating Method Requirements

In swift, Mutating means to change something or modify it. Mutating methods are the methods which we want to change or modify it on class level, for making these types of methods we have to declare with mutating keyword to change its implementation.

 

Following is the example of defining a protocol with a mutating method to change the defined method in adopted classes.

 

protocol Student {

mutating func fullname()

}

class School : Student {

func fullname() {

print("Suresh Dasari")

}

}

var ss = School()

ss.fullname()

When we run above program in swift playground we will get a result like as shown below

 

Suresh Dasari

This is how we can use mutating methods in protocols to modify the functionality of methods based on our requirements.

Swift Protocol Initializer Requirements

Swift allows programmers to directly initialize protocols by conforming to its types. We can declare the initializers as a part of protocol same as a normal initializer, but we won’t use the curly braces or an initializer body.

Syntax of Swift Protocol Initializer

Following is the syntax of defining a protocol initializer in swift programming language.

 

protocol ProtocolName {

init(ParameterName: Int)

}

If you observe the above syntax we defined an initializer (init) method inside of a protocol. Following is the simple example of defining an initializer (init) method inside of protocol in a swift programming language.

 

protocol Student {

init(stuId: Int)

}

This is how we can use initializers in protocols based on our requirements in a swift programming language.

Swift Class Implementations of Protocol Initializer Requirements

We can implement a protocols initializer requirement on a conforming class as either a designated initializer or a convenience initializer. We need to declare a required modifier in initializer implementation like as shown below

 

class SomeClassName: SomeProtocolName {

required init(someParameter: Int) {

// Here is the initializer implementation statements

}

}

protocol Studentprotocol {

init(studentid: Int)

}

class stuclass: Studentprotocol {

required init(studentid: Int) {}

}

If subclass overrides an initializer in super class and also implementing matching required initializer from protocol then we need to define required and override keywords like as shown below.

 

protocol Protocolname {

init(ParameterName: Int)

}

class SuperClass {

init() {

// Initializer implementation

}

}

class SubClass: SuperClass, Protocolname {

// “required” from Protocol, “override” from SuperClass

required override init() {

// Initializer implementation

}

}

Swift Protocols as Types

Generally in swift, protocols does not implement any functions or methods itself. Any protocols which we created will become a type for use in our code.

 

Protocol is a type conforming, we can use protocols in different places where the different types are allowing to declare including.

 

  • We use it in parameter or return type of our functions, methods and initializer.
  • We use in constant, property or variable type.
  • We use in an array, dictionary where the list of items is display.

Following is the example of using protocols as a type in a swift programming language.

 

protocol Number {

associatedtype integertype

func doit(val:integertype) -> integertype

}

class additionint : Number {

func doit(val: Int) -> Int {

return val + 4

}

}

func perform<B:Number>(thing:B, val:B.integertype) -> B.integertype {

return thing.doit(val:val)

}

print(perform(thing: additionint(), val: 33))

If you observe above example we defined a protocol “Number” and a class “additionint”. We adopted a protocol to implement required functions in defined class and here we used an associatedtype keyword to define a type in protocol.

 

When we execute above program in swift playground we will get result like as shown below

 

37

This is how we can use protocols as a type in a swift programming language based on our requirements.

Swift Protocol Inheritance

In Swift, Protocols can inherit one or more protocols and further modify with its on the requirement. The syntax of protocol inheritance is similar to class inheritance, but to list multiple inherited protocols we need to separate them with commas.

Swift Protocol Inheritance Syntax

Following is the syntax of defining protocol inheritance with multiple protocols in a swift programming language.

 

protocol InheritProtocol : FirstProtocol, SecondProtocol

{

// protocol implementation

}

Following is the example of defining a protocol inheritance in swift programming language.

 

protocol Teacher {

var name: String {get set}

var education: String {get set}

func userdetails()

}

protocol Department: Teacher {

var dept: String {get set}

func deptInfo()

}

struct School : Department

{

var name: String = "Suresh Dasari"

var education: String = "B.Tech"

var dept: String = "Software"

func userdetails() {

print("Name: \(name), Education: \(education)")

}

func deptInfo() {

print("Department: \(dept)")

}

}

var ins = School()

print(ins)

ins.userdetails()

ins.deptInfo()

If you observe above example we defined a protocol Teacher and inherited Teacher protocol by another protocol Department and School structure adopted a Department protocol and implemented a defined functions and properties in structure.

 

When we run above example in swift playground we will get a result like as shown below

 

School(name: "Suresh Dasari", education: "B.Tech", dept: "Software")

Name: Suresh Dasari, Education: B.Tech

Department: Software

This is how we can use inheritance with protocols in a swift programming language based on our requirements.

Swift Class-Only Protocols

If we want to limit protocol adoption only to class types then by defining an AnyObject protocol to a protocols inheritance list we can restrict protocol adoption only for classes not for structures or enumerations.

 

Following is the example of defining a protocol with AnyObject to restrict protocol adoption limited to only class.

 

protocol SomeProtocol: AnyObject, SomeIneritingProtocol {

// class only protocol definition goes here

}

The above protocol can be adopted by only class type if we try to adopt it other than a class type like structures or enumerations we will get a compile-time error.

Swift Protocol Composition

In swift, protocol composition is the process to combine multiple protocols into a single protocol. Protocol composition is like defining a temporary protocol that has the combined requirements of all the protocols in the composition.

 

In protocol composition, we can list as many as protocols by separating them using the ampersand (&) like someprotocol & someprotocol2. The protocol composition can contain one class type, which allows us to specify a superclass.

 

Following is the example of defining protocol composition by combining multiple protocols into the single protocol in a swift programming language.

 

protocol Teacher {

var name: String {get set}

var education: String {get set}

}

protocol Department {

var dept: String {get set}

}

struct School : Teacher, Department

{

var name: String

var education: String

var dept: String

}

func userdetails( to user: Teacher & Department) {

print("Name: \(user.name), Education: \(user.education), Department: \(user.dept)")

}

let ins = School(name: "Suresh Dasari", education: "B.Tech", dept: "Software")

userdetails(to: ins)

If you observe above example we defined a two protocols Teacher, Department and those two protocols are adopted by structure called School. We combined multiple protocols (Teacher, Department) into single user using protocol composition.

 

When we run the above program in swift playground we will get a result like as shown below

 

Name: Suresh Dasari, Education: B.Tech, Department: Software

This is how we can combine multiple protocols into a single using protocol composition in a swift programming language based on our requirements.

Swift Checking for Protocol Conformance

Generally, in swift by using is and as operators described in Type Casting can be used to check for protocol conformance and to cast to a specific protocol.

 

The is operator will return true if an instance conforms to a protocol and returns false if it does not.

 

In case if an instance does not conform to the protocol, the as? operator will return an optional value of the protocol’s type.

 

The as! operator forces the downcast to the protocol type and throws a runtime error if the downcast does not succeed.

 

Following is the example of checking for protocol conformance in a swift programming language.

 

protocol Numbers {

var result: Int {get}

} 

class Addition: Numbers {

var a: Int

var b: Int

var result: Int

init(a: Int, b: Int) {

self.a = a

self.b = b

self.result = a + b

}

}

class Subtraction: Numbers {

var x: Int

var y: Int

var result: Int

init(x: Int, y: Int) {

self.x = x

self.y = y

self.result = x - y

}

}

class users {

var name: String

init(name: String) { self.name = name }

}

let Objects: [AnyObject] = [Addition(a: 10, b: 15), Subtraction(x: 10, y: 15), users(name: "Suresh")]

for obj in Objects

{

if let objwithresult = obj as? Numbers {

print("Result: \(objwithresult.result)")

}

else {

print("Object Does Not Contain a Result")

}

}

If you observe above example we defined a multiple classes with or without Numbers protocol and objects in array conforms to the Numbers protocol. The optional value returned by as? Operator is unwrapped with optional binding into a constant called objwithresult. By using objwithresult we can access and print result value.

 

When we run the above program in swift playground we will get a result like as shown below

 

Result: 25

Result: -5

Object Does Not Contain a Result

This is how we can implement protocol conformance in a swift programming language based on our requirements.

Swift Optional Protocol Requirements

We can define optional requirements for protocol by using an optional modifier as a part of the protocol's definition.

 

In swift, both protocol and optional requirements must be marked with the @objc attribute. The @objc protocols can be adopted only by classes that inherit from objective-c classes or other @objc classes and for structures and enumerations not possible to adopt @objc protocols.

 

Following is the example of defining an optional protocol using @objc attribute in a swift programming language.

 

import Foundation

@objc protocol MyProtocol {

@objc optional func FullName()

}

class MyClass : MyProtocol {

@objc func FullName() {

print("Suresh Dasari")

}

}

var mycls = MyClass()

mycls.FullName()

When we run above program in swift playground we will get a result like as shown below

 

Suresh Dasari

This is how we can define optional requirements in protocols based on our requirements in a swift programming language.

Swift Protocol Extensions

Swift allows programmers to extend their protocols to provide a method and property implementation. This feature allows programmers to define protocols behaviors themselves rather than implement at the individual way in a global function.

 

Following is the example of extending the protocol feature in a swift programming language.

 

protocol Welcome {

func welcomemsg()

}

extension Welcome {

func welcomemsg(){

print("Welcome to Tutlane")

}

}

class Hello : Welcome

{

}

var ins = Hello()

ins.welcomemsg()

If you observe above example we are extending the behaviour of the protocol using extension keyword.

 

When we run the above program in swift playground we will get a result like as shown below

 

Welcome to Tutlane

This is how we can use protocols in a swift programming language based on our requirements.