0

I've just learned about extensions and I was wondering, there was an example about extending a protocol. For example, let's say we have the protocol:

protocol CanFly {
    func canFly()
}

which allows all the classes who can fly to basiclly to fly. Now lets say that we use extension to extend the protocol, and we do:

extension CanFly {
    func canEat() {
        print("I can eat")
    }
}

What is the purpose of that if we can just add that func canEat to our protocol? More of those protocols are like an abstract struct so why would we add a func with a body to it?

  • just wanna say if I've made a mess im sorry for that lol, just want to clear out few things about extension <3
Vladyslav Zavalykhatko
  • 15,202
  • 8
  • 65
  • 100
  • it is Swift naming convention to name your functions starting with an lowercase letter – Leo Dabus Apr 20 '20 at 06:02
  • protocols are a contract that if you want that some structures will conform to it they will have to implement the methods that are present on the contract. If you extend a protocol adding a method to it, you are not requiring them to implement that function, you are providing them some functionality. – Leo Dabus Apr 20 '20 at 06:06
  • 1
    [Protocols](https://docs.swift.org/swift-book/LanguageGuide/Protocols.html) – Joakim Danielson Apr 20 '20 at 07:42
  • 1
    You may want to separate some logic and even store it in another file. That's when extensions may be helpful. – dywp Apr 20 '20 at 08:32
  • I see, thank you for the answer <3 –  Apr 20 '20 at 08:35

2 Answers2

0

Per Swift documentation on Protocol Extensions:

Protocols can be extended to provide method, initializer, subscript, and computed property implementations to conforming types. This allows you to define behavior on protocols themselves, rather than in each type’s individual conformance or in a global function.

This means you can run logic within the protocol extension function so you don't have to do it in each class that conforms to the protocol.

Personally, I also find extensions useful to extend the functionality of built-in classes like String or UIViewController since extensions can be called from anywhere in an app. I have some open-source extension snippets you can take a look at if you'd like.

elliott-io
  • 1,394
  • 6
  • 9
0

Extending a protocol is just one of the possible use cases for extensions, really powerful and useful, but might be confusing at the start.

I suggest you looking through this article, as it dives deeper into more mundane, so to speak, ways to use it.

Vladyslav Zavalykhatko
  • 15,202
  • 8
  • 65
  • 100