Sirop4ik
Sirop4ik

Reputation: 5243

Is there a way to know that method is protocol implementation in Swift?

For example, I have such a protocol

public protocol MyProtocol
{
    func foo()
}

Protocol implementation

class MyClass : MyProtocol
{
    public func foo() {...}
}

there is no way to know if the method foo() is a (direct) class method or protocol implementation

So, sometimes (eg:) if a certain class implements few protocols where each of them has few methods it is hard to know which method related to which protocol.

So the question is - is there actually no way to know it?

UPD

I need to know it just for a better understanding of the code and in addition, it is easier to navigate when I know which method related to which protocol.

Upvotes: 1

Views: 244

Answers (1)

Sweeper
Sweeper

Reputation: 271595

When you are writing code, it is usually a good idea to write implementations of protocol methods in their own separate extensions. For example:

class MyClass {
    // implement methods unrelated to any protocols here
}

extension MyClass : Protocol1 {
    // implement the methods in Protocol1
}

extension MyClass : Protocol2 {
    // implement the methods in Protocol2
}

// etc

This way you know exactly what methods belong to which protocol.

However, let's say you are reading someone else's code that you can't change.

In Xcode, you can see if a method in a class implements a protocol by holding the command key and then clicking on its name, then the "quick actions" menu comes up:

enter image description here

If you click on "Jump to definition",

  • you will be taken to the method declaration in the protocol, if the method implements a method declared in a protocol, or
  • you will stay where you are, if it's just a regular old method

Do note that you will also stay where you are, if the method implements a protocol method, but is overridden. So if you see an overridden method, and wants to know if it is a requirement for a protocol or not, you'll have to go to the superclass first.

Or, use AppCode, where there are markers beside these methods:

enter image description here

The "I" markers with a red upwards arrow are what you're looking for. Clicking on them takes you to the declaration in the protocol. For overridden methods, they look no different from regular overridden methods, and you still need to go to the superclass first by clicking on the "O" marker with a red upwards arrow.

The only downside of this is of course, you need to pay for AppCode :(

Upvotes: 1

Related Questions