Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict a protocol to value types only?

Tags:

swift

swift2

Similar in spirit to this question, except, instead of limiting a protocol to only classes, I want to be able to define a protocol that can only be adopted by enums, structs etc.. Is this possible?

like image 833
vopilif Avatar asked Nov 10 '15 04:11

vopilif


People also ask

Is protocol value type or reference type?

A class is always a reference-type, whether you refer to it through a protocol or directly. So assigning a protocol with a reference-type(class) behind it does not copy the class-object, but you rather give out another reference to the object and increases the reference-count which ARC looks at.

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.

CAN protocol have properties?

A protocol can have properties as well as methods that a class, enum or struct conforming to this protocol can implement. A protocol declaration only specifies the required property name and type. It doesn't say anything about whether the property should be a stored one or a computed one.

What is protocol inheritance?

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.


1 Answers

I couldn't find the answer, but through playing around, I've come to the conclusion that you can't. Being that to restrict a protocol to just classes, you precede it with class like

protocol SomeProto: class {
    func structYourStuff() -> Void
}

Making the assumption that this would be consistent among other types, I tried

protocol SomeProto: struct {
    func structYourStuff() -> Void
}

But Xcode gave me five different errors on one line, which brings me to the conclusion that you can't. I could be completely wrong though, I only started learning Swift about a week ago

like image 170
Chris Avatar answered Oct 18 '22 22:10

Chris