Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 484
Yannick Loriot Avatar asked Sep 10 '14 13:09

Yannick Loriot


People also ask

How many protocols can a Swift class adopt?

Swift 4 allows multiple protocols to be called at once with the help of protocol composition.

CAN protocols have properties in Swift?

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.

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 a protocol inherit from a 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

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      // ... } 
like image 155
Mike S Avatar answered Sep 19 '22 13:09

Mike S