Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where SHOULD protocols be declared in swift? [closed]

As far as best practices go, where should a protocol be declared? within the related class or in its own separate file?

Either way would work in theory, but are there any reasons to steer one way or another?

like image 870
Julian B. Avatar asked Aug 12 '16 23:08

Julian B.


1 Answers

I follow a rule of keeping the delegate protocol within the file of the class that contains the delegate property.

The following code outline illustrates keeping the protocol with the property where the delegate will be set.

MyClass.swift:

protocol MyDelegate: class {
    func firstDelegateMethod() 
    func secondDelegateMethod() 
}

class MyClass {
    weak var delegate: MyDelegate?  
}

The delegates are the objects that need to conform to the protocol and are defined by other classes, not the one containing the protocol.

It's helpful to remember that the delegates are the ones doing the work. They do what is needed by what is declared in the protocol.

It can be confusing to keep track of these relationships since the protocol can essentially be placed anywhere. If you follow a consistent pattern like this it will make life easier and your code more manageable.

like image 62
Daniel Zhang Avatar answered Nov 15 '22 19:11

Daniel Zhang