Sweeper
Sweeper

Reputation: 270758

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 @objc to the protocol declaration:

@objc protocol MyProtocol { }

But why can this fix the error?

My guess is that adding @objc 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 @objc prevents me from adding swift types like [String: Any]. I also would like to know is there another way of fixing the error.

Upvotes: 4

Views: 71

Answers (1)

Martin R
Martin R

Reputation: 539675

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.

Upvotes: 4

Related Questions