简体   繁体   中英

What exactly does `: class` do in a protocol declaration?

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?

: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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM