快速向下转换和协议变量 [英] Swift downcasting and protocol variables
问题描述
我有一个包含一个属性的swift协议:
I have a swift protocol that contains one property:
protocol WireframeProtocol: class
{
var rootViewController: UIViewController { get }
}
然后我有一个实现此协议的类因此:
I then have a class that implements this protocol as such:
class MenuWireframe : WireframeProtocol
{
let rootViewController: UIViewController
init()
{
self.rootViewController = MenuViewController(nibName: "MenuViewController", bundle: nil)
(self.rootViewController as! MenuViewController).presenter = MenuPresenter(interactor: MenuInteractor())
}
}
在我的Wireframe类中,变量实际上是类型为MenuViewController但必须声明为UIViewController以确认协议。我必须使用(self.rootViewController as!MenuViewController)将它向下转换为我想要的正确类,以便能够访问其属性。在我上面的简单例子中它很好但是不是很易读,特别是在更复杂的情况下。有没有更好的方法来声明协议变量?
In my Wireframe class the variable is actually of type MenuViewController but has to instead be declared as UIViewController to confirm to the protocol. I have to use (self.rootViewController as! MenuViewController) to downcast it to the correct class I want so as to be able to access its properties. It is fine in my simple example above but is not very readable, especially in more complex situations. Is there a better way to declare the protocol variable?
非常感谢!
推荐答案
是的,通过使用通用协议,有更好的方法。要实现这一点,你必须声明你的协议类似于:
Yes there is a better way and thats by using generic protocols. To implement that you must declare your protocol similar like this :
protocol WireframeProtocol{
typealias RootViewController : UIViewController
var rootViewController: RootViewController { get }
}
然后在你的采用类中将rootViewController类型设置为MenuViewController
then in your adoption class set rootViewController type as MenuViewController
class MenuWireframe : WireframeProtocol{
let rootViewController: MenuViewController
init(){
self.rootViewController = MenuViewController(nibName: "MenuViewController", bundle: nil)
self.rootViewController.presenter = MenuPresenter(interactor: MenuInteractor())
}
}
这篇关于快速向下转换和协议变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!