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?
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.
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 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.
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.
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
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