Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...