`:class`究竟在协议声明中做了什么? [英] What exactly does `: class` do in a protocol declaration?
问题描述
此 SO帖子很好地解释了如何解决创建委托
的问题,即弱
。
This SO post explains pretty well how to solve the issue of creating a delegate
that is weak
.
基本上,有两种方法:
使用 @objc
keyword:
Using the @objc
keyword:
@objc protocol MyClassDelegate {
}
class MyClass {
weak var delegate: MyClassDelegate?
}
使用:class
keyword:
Using the :class
keyword:
protocol MyClassDelegate: class {
}
class MyClass {
weak var delegate: MyClassDelegate?
}
我正在尝试做一些研究,以了解两者之间究竟有什么区别方法是。使用< docs 非常明确code> @objc :
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
:
在Objective-C中可以访问和使用Swift类必须是Objective-C类的后代,或者必须标记为
@objc
。
但是,我找不到有关:class
实际上是什么的一些信息。从细节上考虑整个概念,它实际上并没有多大意义。我的理解是 class
是Swift中用来声明类的关键字。所以,在这里似乎我们使用关键字 class
本身作为协议(因为我们在之后附加它:
协议声明后)。
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
确保只有类可以实现协议。那是任何类,而不仅仅是 NSObject
的子类。另一方面, @objc
告诉编译器使用Objective-C样式的消息传递来调用方法,而不是使用vtable来查找函数。
: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.
这篇关于`:class`究竟在协议声明中做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!