Swift Protocol - Property type subclass

陌路散爱 提交于 2019-12-18 18:51:59

问题


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.

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

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

and

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

where

class LeftPanelView: PanelView {
     ...
}

and (one last piece...)

class PanelView: UIView {
    ...
}

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!


回答1:


The problem is with the setter in the protocol.

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

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.

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

var panelView: PanelView = 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!



来源:https://stackoverflow.com/questions/32231420/swift-protocol-property-type-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!