TagProtocols

Swift – Class

 
Class is something that acts as  a template to represent object properties and behaviour. For example, let us consider a real world object car. This object may contain properties like color, speed, model name and so on. It may have behaviours like accelerate, brake and so on.
Syntax

class className:SuperClass,ConformingProtocol1,..ConformingProtocoln{
   //variables and methods
}

Example

class Car:Vehicle,DrivingProtocol{
var turbo:String
func addTurbo(){
//Add turbo
}
}

 

Swift – Protocols

 

Protocols provides ability for us to define properties and methods that a task should conform to. For example, let us consider we have a Driving protocol. It may have methods and properties like brake and speed that conforming Car class should implement.

Syntax

protocol protocolName{
//methods and properties
}

Example

protocol DrivingProtocol{
var speed: Int { get }
func brake()
}
//Implemetation of protocol in class car
class Car:Vehicle,DrivingProtocol{
   func brake(){
      //Add brake actions
   }
}

Objective C Compatible Protocol Syntax

@objc protocol protocolName{
//methods and properties
optional
//optional methods
}

Example

@objc protocol DrivingProtocol{
var speed: Int { get }
   optional
   func brake()
}
//Implemetation of protocol in class car
class Car:Vehicle,DrivingProtocol{
   //Optional to add brake function
}