Reputation: 3163
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
Reputation: 3163
Answering my own question 3 years later, Swift 4 supports combined class and protocol types:
let delegate: UIViewController & MyDelegateProtocol
Upvotes: 4
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
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:
Upvotes: 4
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