Reputation: 5543
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
}
}
}
Here is what it states on Apple's Swift documentation:
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.
There is no explanation of "@objc class..", only "@objc protocol".
Upvotes: 1
Views: 496
Reputation: 1242
@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.
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).
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.
Upvotes: 1
Reputation: 118741
On this page, it says
If you apply the
objc
attribute to a class or protocol, it’s implicitly applied to the members of that class or protocol. The compiler also implicitly adds theobjc
attribute to a class that inherits from another class marked with theobjc
attribute. Protocols marked with theobjc
attribute can’t inherit from protocols that aren’t.
So, the difference is that it applies implicitly to all members. Also, you'll be prevented from adding @objc
to a generic class.
Upvotes: 1