如何声明具有类型并实现协议的变量? [英] How do I declare a variable that has a type and implements a protocol?

查看:46
本文介绍了如何声明具有类型并实现协议的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用有一个细节视图控制器的协议,声明它们必须有一个 viewModel 属性:

My app has a protocol for detail view controllers, stating they must have a viewModel property:

protocol DetailViewController: class {
    var viewModel: ViewModel? {get set}
}

我还有几个不同的类来实现协议:

I also have a few different classes that implement the protocol:

class FormViewController: UITableViewController, DetailViewController {
    // ...
}

class MapViewController: UIViewController, DetailViewController {
    // ...
}

我的主视图控制器需要一个属性,该属性可以设置为任何实现 DetailViewController 协议的 UIViewController 子类.

My master view controller needs a property that can be set to any UIViewController subclass that implements the DetailViewController protocol.

不幸的是,我找不到有关如何执行此操作的任何文档.在 Objective-C 中,这将是微不足道的:

Unfortunately I can't find any documentation on how to do this. In Objective-C it would be trivial:

@property (strong, nonatomic) UIViewController<DetailViewController>;

Swift 中似乎没有任何可用的语法来执行此操作.我最接近的是在我的类定义中声明一个泛型:

It appears that there isn't any syntax available in Swift to do this. The closest I've come is to declare a generic in my class definition:

class MasterViewController<T where T:UIViewController, T:DetailViewController>: UITableViewController {
    var detailViewController: T?
    // ...
}

但后来我收到一条错误消息,指出‘MasterViewController’类没有实现其超类所需的成员"

But then I get an error saying that "Class 'MasterViewController' does not implement its superclass's required members"

这看起来在 Swift 中应该和在 Objective-C 中一样容易,但是我找不到任何可以建议我如何去做的任何地方.

This seems like it should be as easy to do in Swift as it is in Objective-C, but I can't find anything anywhere that suggests how I might go about it.

推荐答案

从 Swift 4 开始,您现在可以这样做.

As of Swift 4, you can now do this.

Swift 4 实现了 SE-0156(类和子类型存在).

Swift 4 implemented SE-0156 (Class and Subtype existentials).

相当于这个 Objective-C 语法:

The equivalent of this Objective-C syntax:

@property (strong, nonatomic) UIViewController<DetailViewController> * detailViewController;

现在在 Swift 4 中看起来像这样:

Now looks like this in Swift 4:

var detailViewController: UIViewController & DetailViewController

本质上,您可以定义一个变量符合的类,以及它实现的 N 个协议.有关更多详细信息,请参阅链接文档.

Essentially you get to define one class that the variable conforms to, and N number of protocols it implements. See the linked document for more detailed information.

这篇关于如何声明具有类型并实现协议的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆