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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With