In Objective-C, it's possible to write something like that:
@property(retain) UIView<Protocol1, Protocol2, ...> *myView;
But how can I write this code in swift?
I already know how to make a property conform to many protocols, but it does not work by using the inheritance:
var myView: ??? protocol<Protocol1, Protocol2, ...>
Edit:
I use many UIView
subtypes like UIImageView
, UILabel
or others, and I need to use some of the UIView
properties plus some methods defined in the protocols. In the worst case I could create a UIViewProtocol
with the needed properties, but I would know if it is possible in Swift to declare a property/variable with a type and some protocol to conform with.
Swift 4 allows multiple protocols to be called at once with the help of protocol composition.
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.
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.
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.
You can do this with a generic class using a where clause:
A where clause enables you to require that an associated type conforms to a certain protocol, and/or that certain type parameters and associated types be the same.
To use it, make the class your property is defined in a generic class with a type constraint to check if the type parameter for your property matches your desired base class and protocols.
For your specific example, it could look something like this:
class MyViewController<T where T: UIView, T: Protocol1, T: Protocol2>: UIViewController { var myView: T // ... }
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