Swift协议 - 属性类型子类 [英] Swift Protocol - Property type subclass

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

问题描述

我正在定义一个名为 PanelController 的协议,其中我想存储 PanelView PanelView 本身是 UIView 的子类,并定义了面板的基本结构。我有三个不同的视图,子类 PanelView LeftPanel MidPanel ,和 RightPanel 。对于每个面板,我想定义一个 xxxPanelController (左,中,右),它符合 PanelController 协议。

I'm defining a protocol called PanelController in which I'd like to store a PanelView. PanelView itself is a subclass of UIView and defines the basic structure of panel. I have three different views that subclass PanelView: LeftPanel, MidPanel, and RightPanel. For each of those panels I'd like to define a xxxPanelController (left, mid, right) that conforms to the PanelController protocol.

我正在运行的问题是协议和 xxxPanelController

The issue I'm running up against is in the protocol and xxxPanelController

protocol PanelController {
    var panelView: PanelView { get set }
    ...
}

class LeftPanelController: UIViewController, PanelController {
    var panelView = LeftPanelView()
    ...
}

其中

class LeftPanelView: PanelView {
     ...
}

和(最后一件......)

and (one last piece...)

class PanelView: UIView {
    ...
}

我收到一条错误消息: LeftPanelController不符合协议PanelController ,原因很明显: pan elView 的类型为 LeftPanelView 不是 PanelView 。这似乎真的仅限于我,因为 LeftPanelView PanelView 的子类,所以它应该正常工作!但事实并非如此!

I get an error saying that: LeftPanelController does not conform to protocol PanelController for an obvious reason: panelView is of type LeftPanelView not PanelView. This seems really limited to me, though, because LeftPanelView is a subclass of PanelView so it should just work! But it doesn't!

有人可以向我解释为什么会这样,如果有人能想出一个,可能的解决方法吗?谢谢!

Can someone explain to me why this is, and if anyone can come up with one, a possible workaround? Thanks!

推荐答案

问题在于协议中的setter。

The problem is with the setter in the protocol.

假设您要从 LeftPanelController 获取 panelView 。没关系,因为 LeftPanelView 可以做任何事情 PanelView 可以做(以及更多)。

Let's say you want to GET the panelView from LeftPanelController. That's fine, because LeftPanelView can do everything PanelView can do (and more).

如果你想设置 panelView LeftPanelController ,你可以给它任何的PanelView 。因为您将 panelView 变量定义为 LeftPanelView ,所以setter有时可能会失败。

If you want to SET the panelView of LeftPanelController though, you can give it any PanelView. Because you're defining the panelView variable as a LeftPanelView, the setter could sometimes fail.

要解决此问题,您可以在 LeftPanelController 中执行以下操作:

To fix this, you could do the following in LeftPanelController:

var panelView: PanelView = LeftPanelView()

这意味着您将无法访问任何特定于 LeftPanelView 的方法或属性,而无需先将其强制转换。如果这不是问题,那么这应该可以解决您的问题!

The implication of this is that you won't be able to access any methods or properties that are specific to LeftPanelView without casting it first. If that's not an issue, then this should fix your problem!

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

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