In Swift, what does it mean for protocol to inherit from class keyword?
e.g.
protocol MyDelegate: class {
}
A Swift protocol can inherit from other protocols, requiring conforming types to provide implementations for all the property and method requirements in the entire protocol hierarchy.
One protocol can inherit from another in a process known as protocol inheritance. Unlike with classes, you can inherit from multiple protocols at the same time before you add your own customizations on top. Now we can make new types conform to that single protocol rather than each of the three individual ones.
You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.
The gist of Starscream's answer is correct, but it misses the why which I think is important here. It comes down to ARC and memory management.
Swift is a language of reference types and value types. Classes are reference types, while everything else is a value type. Effectively, we're not really specifying that the protocol inherits from class
... it's more like we're specifying that the protocol can only be implemented by reference types.
And why is that important?
It's important, because without it, we can't use the weak
keyword with the protocol.
protocol ExampleProtocol {}
class DelegatedClass {
weak var delegate: ExampleProtocol?
}
This generates the error:
'weak' cannot be applied to non-class type 'ExampleProtocol'
And why not? Because the weak
keyword only makes sense with reference types to which ARC applies. ARC does not apply to value types. And without specifying our protocol with class
, we cannot guarantee that our delegate
property is set to a reference-type. (And if we don't use weak
, we're most likely creating a retain cycle.)
From the Apple docs:
You can limit protocol adoption to class types (and not structures or enumerations) by adding the class keyword to a protocol’s inheritance list.
Example:
protocol AProtocol: class {
}
//Following line will produce error: Non-class type 'aStruct' cannot conform to class protocol 'AProtocol'
struct aStruct: AProtocol {
}
The line declaring the structure will spit an error. Following line will produce error:
Non-class type '
aStruct
' cannot conform to class protocol 'AProtocol
'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With