3

This SO post explains pretty well how to solve the issue of creating a delegate that is weak.

Essentially, there are 2 approaches:

Using the @objc keyword:

@objc protocol MyClassDelegate { } class MyClass { weak var delegate: MyClassDelegate? } 

Using the :class keyword:

protocol MyClassDelegate: class { } class MyClass { weak var delegate: MyClassDelegate? } 

I am trying to do some research to understand what exactly the differences between the two approaches are. The docs are pretty clear about using @objc:

To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc.

However, nowhere I found some information about what :class actually does. Considering the whole notion in detail, it actually doesn't make a lot of sense to. My understanding is that class is a keyword in Swift to declare classes. So, here it seems like we are using the keyword class itself as a protocol (as we're appending it after the : after the protocol declaration).

So, why does this even work syntactically and what exactly does it do?

11

1 Answer 1

5

:class ensures that only classes can implement the protocol. And that's any class, not just subclasses of NSObject. @objc, on the other hand, tells the compiler to use Objective-C-style message passing to call methods, instead of using a vtable to look up functions.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot for your answer! do you have any (official) resources explaining why we can use : class in a protocol declaration? the syntax seems pretty weird to me, really would like to read some more about this.
Do you mean just Apple's Swift documentation?
oh yeah, that was pretty much what I was looking for, thanks!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.