I want this protocol:
protocol AddsMoreCommands { /* ... */ }
only to be adopted by classes that inherit from the class UIViewController
. This page tells me I can specify that it is only adopted by a class (as opposed to a struct) by writing
protocol AddsMoreCommands: class { }
but I cannot see how to require that it is only adopted by a particular class. That page later talks about adding where
clauses to protocol extensions to check conformance but I cannot see how to adapt that either.
extension AddsMoreCommands where /* what */ { }
Is there a way to do this? Thanks!
A protocol defines a blueprint of methods, properties, and other requirements. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. But there would be a time when you want to restrict protocols to be adopted by a specific class.
A protocol may specify that only a class can implement it through using the class keyword in its inheritance list. This keyword must appear before any other inherited protocols in this list. If a non-class type tries to implement ClassOnlyProtocol , a compiler error will be generated.
Swift 4 allows multiple protocols to be called at once with the help of protocol composition.
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.
protocol AddsMoreCommands: class { // Code } extension AddsMoreCommands where Self: UIViewController { // Code }
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