Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require that a protocol can only be adopted by a specific class

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!

like image 831
emrys57 Avatar asked Feb 01 '16 15:02

emrys57


People also ask

Can we make protocol only class specific struct can not adopt it?

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.

What is class only protocol?

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.

How many protocols can a Swift class adopt?

Swift 4 allows multiple protocols to be called at once with the help of protocol composition.

What's the difference between a protocol and a class in Swift?

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.


1 Answers

protocol AddsMoreCommands: class {     // Code }  extension AddsMoreCommands where Self: UIViewController {     // Code } 
like image 176
Roee84 Avatar answered Oct 13 '22 22:10

Roee84