Search Your Question

What is protocol extension? Why Swift called as Protocol Oriented Language?

Ans : It is same as we extend class to add functions to existing class. Here we can add functions to existing protocol by extending protocol.

protocol proto {
   func add()
}

extension proto {
   func sub()

}

Benefits :

1.

We can also add default body to protocol extension function. So any type which confirm protocol has choice to implement that method or not. In other words we can say that it become optional method. Protocol extension method must have body.

protocol proto {
    func add()
}

extension proto {
    func add()  {
        print("add method called")
    }
    
    func sub() { }
}

class cp : proto {
   
}

let pq = cp()
pq.add()



Output : 
add method called

2. 

We can confirm multiple protocol and we can say that is multiple inheritance.

protocol proto1 {
    func add()
}

protocol proto2 {
    func sub()
}

class cp : proto1,proto2 {
    func add() {
        
    }
    
    func sub() {
        
    }
}

let pq = cp()
pq.add()

3. 

We can make protocol comparable due to protocol extension.

protocol Score: Comparable {
  var value: Int { get }
}

struct RacingScore: Score {
  let value: Int
  
  static func <(lhs: RacingScore, rhs: RacingScore) -> Bool {
    lhs.value < rhs.value
  }

}

4.

Mutating function in protocol to change value of protocol.

Struct is value type. You can only change property of struct only if property declared as var and instance is also var.



So, if we add mutating before func, it allow to change value in struct type. Same thing also can be done with protocol and protocol extension.

5.

There's also obviously anything that you can do with generics in Swift that couldn't be done in Objective C.  So for instance the Indexable protocol could be extended to have a function that returned the index range length which might only apply if the index is an Int like this:

extension Collection where Self.Index == Int
{
  func length () -> Int
  {
     return endIndex - startIndex
  }

}


Due to this very powerful features of protocol in Swift, Swift is called Protocol Oriented  Programming Language.


No comments:

Post a Comment

Thanks