Protocol Extensions in Swift

Swift Protocol

01 May 2020 . 1 min read       @gurjitpt


A protocol can defines a set of methods that can be adopted by any class, but we can’t write code inside.On the other hand, extensions gives us the power to write code inside methods, but it can only used for one type.

In Protocol Extensions, we can extend protocols to provide implementations to all conforming types rather than extending a particular type.

For example, we have an array named oddNumbers contains odd numbers and a Set named evenNumbers that contains even numbers.

let oddNumbers: [Int] = [1,5,23,91]
let evenNumbers: Set = [34,56,12,78,22]

Now, we have protocol Collection that can be extended to provide countItems() method which returns total numbers of items.

extension Collection {
    func countItems() -> Int {
         return count
    }
}

Both conforming types gain countItems method by extending the protocol and prints total number of items available.

print(oddNumbers.countItems())
print(evenNumbers.countItems())

Protocol extensions can’t extend or inherit from another protocol.

Thanks!


Next Posts

Difference between Struct and Classes explained in Swift

Structures and Classes are basic templates for any application which consists of properties and methods implements for behaviour .You can define structure or class..

May 06, 2020 . 2 min read     Swift

Read More »

Custom Operators in Swift Empty space for void

Swift provides a very useful feature which is to define your own custom operators. It is a very confusing topic in the beginning but it is very powerful to use.It increases our code readability..

May 04, 2020 . 2 min read     Swift

Read More »

The ultimate guide to iOS Unit Testing with Swift and Xcode

Unit testing is a testing method where you can test “unit” of code whether it is working as you want or not. In Xcode, use XCTest framework to perform unit tests.

Jun 29, 2020 . 2 min read     Xcode Testing

Read More »