Swift Protocol - Property type subclass

前端 未结 1 1189
陌清茗
陌清茗 2021-01-01 15:47

I\'m defining a protocol called PanelController in which I\'d like to store a PanelView. PanelView itself is a subclass of UIVie

1条回答
  •  攒了一身酷
    2021-01-01 15:49

    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!

    0 讨论(0)
提交回复
热议问题