smashkins
(Smashkins)
February 6, 2019, 6:53pm
12
Quoting Matt Neuburg:
A protocol declared with the keyword class after the colon after its name is a class protocol, meaning that it can be adopted only by class object types:
protocol SecondViewControllerDelegate : class {
func accept(data:Any!)
}
(There is no need to say class if this protocol is already marked @objc ; the @objc attribute implies that this is also a class protocol, because classes are the only Objective-C object type.)
A typical reason for declaring a class protocol is to take advantage of special memory management features that apply only to classes
class SecondViewController : UIViewController {
weak var delegate : SecondViewControllerDelegate?
// ...
}
The keyword weak marks the delegate property as having special memory management that applies only to class instances. The delegate property is typed as a protocol, and a protocol might be adopted by a struct or an enum type. So to satisfy the compiler that this object will in fact be a class instance, and not a struct or enum instance, the protocol is declared as a class protocol.
In Swift 4 or later, you might alternatively take advantage of classprotocol composition to accomplish the same thing:
class SecondViewController : UIViewController {
weak var delegate : (NSObject & SecondViewControllerDelegate)?
// ...
}
That's legal even if SecondViewControllerDelegate has no class designation, because the compiler knows that the object assigned to the delegate property will derive from NSObject, in which case it is a class instance.
But... the 0156 proposal says:
This proposal merges the concepts of class
and AnyObject
, which now have the same meaning: they represent an existential for classes. To get rid of the duplication, we suggest only keeping AnyObject
around. To reduce source-breakage to a minimum, class
could be redefined as typealias class = AnyObject
and give a deprecation warning on class
for the first version of Swift this proposal is implemented in. Later, class
could be removed in a subsequent version of Swift.
0156 proposal
2 Likes