UberJason
UberJason

Reputation: 3163

How to declare a property of a particular class which is also protocol conformant?

Suppose I want to create a property which is a subclass of UIViewController and also conformant to the protocol MyDelegateProtocol. In Objective-C I would write something like:

@property (strong, nonatomic) UIViewController<MyDelegateProtocol> *delegate;

However, I'm not sure how to write this in Swift. I know how to declare a property which is protocol-conformant, or a property which is of a particular type:

let delegate : MyDelegateProtocol?
let delegate : UIViewController?

But I can't quite figure out how to make it do both. If I try something like:

let delegate : UIViewController<MyDelegateProtocol> ?

Then I get a compiler error about Cannot specialize non-generic type 'UIViewController'. Probably because I'm wandering into the land of generics now. I've tried looking through the Swift book on protocols and other Stack Overflow questions regarding protocols, but I haven't found quite what I'm looking for.

Upvotes: 11

Views: 1072

Answers (4)

UberJason
UberJason

Reputation: 3163

Answering my own question 3 years later, Swift 4 supports combined class and protocol types:

let delegate: UIViewController & MyDelegateProtocol

Upvotes: 4

UberJason
UberJason

Reputation: 3163

Answering my own question a year and a half later to point anyone in the future to this article, which basically answers the question in Swift 2. It's not strictly possible, but using protocol extensions you can get pretty close.

Upvotes: 1

drewag
drewag

Reputation: 94803

First of all, I think this is a code smell. If you want a delegate to be multiple things, there is most likely a separation of concerns problem.

With that said, if you still want to do this, there isn't a way in Swift. You have a few options though:

  1. Add the required UIViewController methods to your delegate protocol (my favorite option)
  2. Create a superclass for your view controller that is a subclass of UIViewController and implements MyDelegateProtocol. Declare your variable as that type
  3. Store two references to your "delegate". One is of the MyDelegateProtocol and the other is of UIViewController
  4. Make your class generic, but this will not be accessible from Objective-C

Upvotes: 4

jtbandes
jtbandes

Reputation: 118771

One option would be to parameterize your whole class; unfortunately, template classes can't be used from Obj-C.

class MyClass<Delegate: protocol<UIViewController, MyDelegateProtocol>> {
    ...
    let delegate: Delegate?
    ...
}

Upvotes: 0

Related Questions