Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class-Only Protocols in Swift

I want some of my classes (not all) to conform using 'Class-Only Protocols' from docs. What I am doing is

protocol RefreshData: class, ClassA, ClassB {     func updateController() } 

and I am getting the errors

non class type 'RefreshData cannot inherit from classA non class type 'RefreshData cannot inherit from classB 

I'm not sure I am following exactly as in the docs. Does anyone have any ideas about this?

like image 877
tonytran Avatar asked Jul 08 '16 15:07

tonytran


People also ask

What is class protocol in Swift?

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.

How many protocols can 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.

CAN protocol inherit from class Swift?

Protocols allow you to group similar methods, functions, and properties. Swift lets you specify these interface guarantees on class , struct , and enum types. Only class types can use base classes and inheritance from a protocol.


1 Answers

Swift 4 allows you to combine types, so you can have your protocol and then create, for example, a type alias to combine it with a specific class requirement.

For (a contrived) example:

typealias PresentableVC = UIViewController & Presentable 

For the presented code:

The problem is that you're trying to limit to specific classes and Swift can't do that (at the moment anyway). You can only limit to classes and inherit from other protocols. Your syntax is for protocol inheritance but you're trying to use it as a class limitation.

Note that the purpose of class protocols is:

Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics.

like image 167
Wain Avatar answered Oct 14 '22 21:10

Wain