Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...