如何声明一个符合协议的特定类的属性? [英] How to declare a property of a particular class which is also protocol conformant?
问题描述
假设我想创建一个属性,它是UIViewController的子类,并且符合协议MyDelegateProtocol。在Objective-C中,我会写如下:
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;
但是,我不知道如何在Swift中写这个。我知道如何声明一个符合协议的属性,或者一个特定类型的属性:
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> ?
然后我得到一个关于的编译器错误不能专门化非泛型类型'UIViewController
。可能是因为我现在正在徘徊于仿制药的土地上。我已经尝试查阅Swift关于协议的协议和其他Stack Overflow问题的书,但我还没有找到我正在寻找的东西。
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.
推荐答案
3年后回答我自己的问题,Swift 4支持组合类和协议类型:
Answering my own question 3 years later, Swift 4 supports combined class and protocol types:
let delegate: UIViewController & MyDelegateProtocol
这篇关于如何声明一个符合协议的特定类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!