我在Swift中遇到这个设计问题。这是我的根类及其子类:

enum VisualItemType {
    case video, picture, text,...
}

class VisualItem {

   public var itemType: VisualItemType
   ...
}

class PictureItem:VisualItem {
   private var subItems:[PictureItem OR TextItem But NOT VideoItem]? //Overlay of picture can be picture or text but not video
}

class VideoItem: VisualItem {
   private var subItems:[VisualItem]? //Overlay of video can be any type of visual item

}
如何在Swift中完全实现PictureItem的子项而不创建新的子类型枚举?

最佳答案

您可以通过引入仅TextItemPictureItem符合的新协议来做到这一点:

protocol PictureOverlayable: VisualItem {}

class TextItem: VisualItem, PictureOverlayable {}

class PictureItem: VisualItem, PictureOverlayable {
   private var subItems: [PictureOverlayable]?
}

关于ios - Swift子类复杂子类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64044012/

10-09 10:17