hnh hnh - 4 years ago 288
Swift Question

How can I make a weak protocol reference in 'pure' Swift (w/o @objc)

Weak references don't seem to work in Swift unless a protocol is declared as @objc, which I don't want in a pure Swift app :-)

This code gives a compile error ('weak' cannot be applied to non-class type 'MyClassDelegate'):

class MyClass {
weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate {
}


I need to prefix the protocol with @objc, then it works.

Question: What is the 'pure' Swift way to accomplish a weak delegate?

Answer Source

Update (Beta 5): Xcode / Swift Beta 5 has changed how do you declare the class requirement for a protocol. Instead of using @class_protocol you now need to declare the type of the protocol as class.

With the new syntax, the sample code I posted with the original answer would read:

protocol ProtocolNameDelegate: class {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}

The idea is the same, but the syntax is perhaps a little bit cleaner.

Original answer (valid until Beta 5):

I believe that the correct way to implement the delegate pattern is to mark your protocol with the attribute class_protocol

From the Swift Programming Language Book:

“class_protocol Apply this attribute to a protocol to indicate that the protocol can be adopted by class types only. If you apply the objc attribute to a protocol, the class_protocol attribute is implicitly applied to that protocol; there’s no need to mark the protocol with the class_protocol attribute explicitly.”

My understanding is that using that attribute, you guarantee that this protocol will be used only on classes and no other stuff like enums or structs. Also, you can see that the objc attribute implies the class_protocol one, that is why it works when you use it.

To put a code sample:

@class_protocol protocol ProtocolNameDelegate {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download