Yannick L. Yannick L. - 4 months ago 14
Swift Question

Swift: Property conforming to a specific class and in the same time to multiple protocols

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 conforms to many protocol, but not by using the inheritance over:

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.

Answer

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

    // ...
}
Comments