Swift Protocol and Implementation

Protocols in Swift , define requirements that has to be implemented by a Class adopting or conforming to it.

Protocols can be adopted by a Class , Structure or Enumeration , all of which can actually implement them based on the requirements. But, in one scenario you can't adopt protocol for Structure and Enumeration. Please go through the entire article for further understanding.


Lets consider a simple example with Inheritance and Requirement (Protocol defines Requirements).


Object Inheritance.
Department Object is inherited by Administration , Finance and Human Resource Department. So all the departments will have inherited properties like departmentName and departmentId.

Protocol.
Protocol define the requirements. These requirements can be required or optional. requirements If you notice in the design listed below, you will notice two type's for requirements.

1) Required 

func dressCode(departmentType: Int) -> UIColor

func numberOfEmployees() -> Int 

2) Optional 

func employeesInRange(fromDate: Date, toDate: Date) -> Int






Department.swift
import Foundation

class Department:NSObject {
    var departmentName:String! = ""
    var departmentId:String! = ""
    

}


DepartmentProtocol.swift
import Foundation
import UIKit

@objc protocol DepartmentProtocol {

    
    func dressCode(departmentType:Int) -> UIColor
    
    func numberOfEmployees()->Int
    
    @objc optional func employeesInRange(fromDate:Date,toDate:Date) -> Int
}


Administration.swift
class Administration: Department , DepartmentProtocol {
    
    func dressCode(departmentType: Int) -> UIColor {
        return UIColor.blue
    }

    func numberOfEmployees() -> Int {
        return 4
    }
    
}


Finance.swift
import Foundation
import UIKit

class Finance: Department,DepartmentProtocol {
    
    func dressCode(departmentType: Int) -> UIColor {
        return UIColor.red
    }
    
    func numberOfEmployees() -> Int {
        return 10
    }
    
    func employeesInRange(fromDate: Date, toDate: Date) -> Int {
        return 5
    }
}


Observation's code

employessInRange is implemented in Finance.swift but not in Administration.swift. As that specific requirement is marked as optional.  Optional Requirements helps to write a code that interoperates with Objective C. Swift does not provide a way to write optional requirements directly. Hence we have to mention it with Objective C attribute.

@objc is the declaration attribute.

Note: 
- It is required both Protocol and the requirement  (i.e function employeesInRange) must be marked with @objc
- @objc protocol can be adopted only by the classes that inherit from Objective-C.  Hence, can't @objc can't be adopted by Structure and Enumeration in that scenario.


Comments

Popular posts from this blog

hitTest on iOS to identify the view being hit

CMTimeMakeWithSeconds explained

Custom Editing Control for UITableViewCell , like iPhone Mail Appliation