需要澄清“@objc类”在Swift [英] Need clarification on "@objc class" in Swift
问题描述
我理解@objc属性对协议的作用。我不明白是为什么它被添加到类,如下面的例子:
I understand what the "@objc" attribute does for protocols. What I don't understand is why it is added to classes, such as in the following example:
@objc protocol CounterDataSource {
optional func incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int { get }
}
@objc class Counter {
var count = 0
var dataSource: CounterDataSource?
func increment() {
if let amount = dataSource?.incrementForCount?(count) {
count += amount
} else if let amount = dataSource?.fixedIncrement {
count += amount
}
}
}
这里是它对苹果的Swift文档说的:
Here is what it states on Apple's Swift documentation:
注意,@objc协议只能被类采用,或枚举。如果您将协议标记为@objc以指定可选要求,您将只能将该协议应用于类类型。
Note also that @objc protocols can be adopted only by classes, and not by structures or enumerations. If you mark your protocol as @objc in order to specify optional requirements, you will only be able to apply that protocol to class types.
没有解释@objc class ..,只有@objc protocol。
There is no explanation of "@objc class..", only "@objc protocol".
推荐答案
@objc
对类声明意味着注释的类将暴露给Objective-C运行时。虽然有其他隐含的差异,但我认为这是最重要的一个。
@objc
on class declarations means the annotated class will be exposed to the Objective-C runtime. There are other implicit differences though, but I think this is the most important one.
您可以尝试从纯Swift类(不是NSObject的子类)中省略注释,然后您无法在Objective-C代码中使用此类将不会出现在您的Objective-C代码使用的gented头文件中)。
You can try to omit the annotation from a pure Swift class (not a subclass of NSObject), then you are unable to use this class in Objective-C code (it won't appears in the genrated header file used by your Objective-C code).
注意,任何继承 NSObject
或其任何子类的类都会自动)标记为 @objc
。因此,将 UIViewController
的子类显式标记为 @objc
没有意义,因为Swift编译器为你。
Note that any classes inheriting NSObject
or any of its subclasses will automatically(implicitly) be marked @objc
. So it does not make sense to explicitly mark say a subclass of UIViewController
as @objc
, because the Swift compiler does it for you.
这篇关于需要澄清“@objc类”在Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!