Sweeper Sweeper - 1 year ago 134
Swift Question

Why can I declare @objc protocols as weak properties, but not swift protocols?

I found out that if I created a protocol like this:

protocol MyProtocol { }

I can't do this:

weak var myVar: MyProtocol?

And I found the way to fix this, which is adding
to the protocol declaration:

@objc protocol MyProtocol { }

But why can this fix the error?

My guess is that adding
prevents structs to conform to the protocol, so the value of the variable is gurranteed to be a reference type. Am I right?

Also, adding
prevents me from adding swift types like
[String: Any]
. I also would like to know is there another way of fixing the error.

Answer Source

Weak references can only be created for reference types, i.e. instances of a class, not for value types (struct or enums).

If you declare the protocol as a "class-only protocol"

protocol MyProtocol : class { }

then you can declare a weak variable of that type:

weak var myVar: MyProtocol?

In your case

@objc protocol MyProtocol { }

declares a protocol which can only be adopted by NSObject subclasses or other @objc classes, so that is implicitly a class-only protocol.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download