1

Whether I do:

protocol SomeProtocol{}

extension SomeProtocol {
  func sayHi(toUser user: String) {
    print("Hi \(user)")
}

OR

protocol SomeProtocol{
  func sayHi(toUser user: String)
}

extension SomeProtocol {
  func sayHi(toUser user: String) {
    print("Hi \(user)")
}

I can conform this protocol in my class:

class MyClass: SomeProtocol {
  sayHi(toUser: "Minion")
}

Output will be: Hi Minion, whether I use approach 1 or 2. What is the difference of adding vs not adding definition of a function in my protocol?

Hamish
  • 78,605
  • 19
  • 187
  • 280
u7568924
  • 83
  • 1
  • 9
  • 1
    There is a difference: See https://stackoverflow.com/questions/34847318/swift-protocol-extension-method-dispatch-with-superclass-and-subclass or https://oleb.net/blog/2016/06/kevin-ballard-swift-dispatch/. – Martin R Jul 14 '17 at 12:04
  • ok @MartinR understood – u7568924 Jul 14 '17 at 12:24

2 Answers2

0

extension is , by all means, an extension for classes, protocols, etc.

In your case, you are adding extension to your protocol, so your extended method will be part of your protocol. That's why your method 1 and 2 make no differences and print out the right thing

Fangming
  • 24,551
  • 6
  • 100
  • 90
0

You write an extension to the protocol to implement a default behavior for that function (or property) when a type adheres to that protocol. If you tell a type to adhere to a protocol and you provide a default behavior for that type, that type doesn't necessarilly have to implement this function, and you don't need to tell that type that it has to implement a function. This would be doubling your effort and you want to write protocols to be more efficient in your code writing.

So, when providing a default implementation in an extension, you have already told the type adhering to the protocol that there is a function that it can use and it has a default implementation it can use or override.

MacUserT
  • 1,760
  • 2
  • 18
  • 30