In Swift, if I create a delegate protocol, it can be conformed to by class and struct.
protocol MyDelegate {
// Can be conformed to by class or struct
}
The issue comes up when I declare the delegate. If the delegate is a class instance, I want the variable to be weak to avoid retain cycle. If it is a struct, there is no such need - in fact, Swift won't allow me to make the delegate variable weak. Note: I know how to create a weak delegate, but the key question is - if you create a delegate protocol that can be weak, unless you make it class-conforming only, you cannot enforce retain cycle.
class MyClass {
// Want weak var here to avoid cyclical reference
// but Swift won't allow it because MyDelegate can be
// conformed by struct as well. Dropping weak means
// cyclical reference cannot be prevented
weak var delegate: MyDelegate?
}
class MyConformingClass: MyDelegate {
}
or
struct MyConformingStruct: MyDelegate {
}
It seems like we need to declare the protocol to be for class only at all times like this because a non regular delegate protocol cannot prevent retain cycles:
protocol MyDelegate: class {
}
The fact that Swift allows you to shoot yourself in the foot this way seems to go against its design philosophy in safety.
protocol MyClassDelegate : class, MyDelegate { }
and thenweak var delegate : MyClassDelegate?
. – Martin R