UIViewController 子类的 Swift 协议 [英] Swift protocol for UIViewController subclasses

查看:72
本文介绍了UIViewController 子类的 Swift 协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以声明一个协议并定义符合它的对象类型?

Is it possible to declare a protocol and also define the type of object that can conform to it?

我想在我的项目中的 UIViewController 的各种不同子类中配置一组闭包.(它们都是相关的).

I have a set of closures that I'd like to configure in various different subclasses of UIViewController in my project. (They are all related).

我想要一个工厂函数来创建正确类型的 UIViewController 子类,然后将其作为协议类型返回.

I'd like to have a factory function that creates the correct type of UIViewController subclass but then returns it as a protocol type.

这样我就可以配置各种闭包并将视图控制器推送到导航控制器上.

That way I can then configure the various closures and push the view controller onto the navigation controller.

我可以……

返回 UIViewController 超类并将其推送到导航堆栈上,但随后无法正确设置闭包,因为编译器不知道它符合协议.

Return the UIViewController superclass and push it onto the navigation stack but then not be able to set the closures properly as the compiler doesn't know it conforms to the protocol.

或...

返回协议类型,我可以正确设置闭包,但编译器不知道它是 UIViewController 子类,因此我无法将其推送到导航控制器上.

Return the protocol type and I'm able to set the closures properly but then the compiler doesn't know that it's a UIViewController subclass so I can't push it onto the navigation controller.

有两种方法吗?

谢谢

推荐答案

在 Objective C 中,你可以像这样声明一个变量:

In Objective C you were able to declare a variable like this:

UIViewController <Protocol> *variable;

不幸的是,这在 Swift 中是不可能的,考虑到 Swift 是面向协议的,这很奇怪.

Unfortunately, this is not possible with Swift, which considering how protocol-oriented Swift is, it's very strange.

这很不舒服,因为就像你发现的那样,编译器不能同时知道类和协议,所以你必须强制转换两次,你必须检查对象是否是允许的类,并且必须在您的代码中记录它以防止人们发送错误类型的对象.

This is pretty uncomfortable because like you found out, the compiler can't be aware of both the class and the protocol at the same time, so you have to cast twice, you have to check that the object is of the allowed class at runtime, and have to document it in your code to prevent people from sending the wrong kind of object.

这篇关于UIViewController 子类的 Swift 协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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