Swift 子类复杂子类型

Swift subclasses complex subtype

我在 Swift 中遇到了这个设计问题。这是我的根 class 和它的子classes:

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]?
}