ios - swift 协议(protocol) : Adding Protocol conformance to an Instance

标签 ios swift protocols swift-protocols

我正在尝试了解如何在实例具有特定值的情况下向实例添加协议(protocol)一致性。这是我试图理解的“愚蠢”示例。

enum TypeOfFigure {
  case square, circle, triangle
}

protocol Figure {
    var type: TypeOfFigure { get }
}
protocol Square {}
protocol Circle {}
protocol Triangle {}


class FigureType: Figure {
    let type: TypeOfFigure

    init (type: TypeOfFigure) {
        self.type = type
        switch type {
        case .square: //extension self: Square {}
        case .circle: //extension self: Circle {}
        case .triangle: //extension self: Triangle {}
        }
    }

}

最佳答案

我建议另一种方法

你可以使用工厂方法:

class FigureTypeFactory {
    static func createFigure(withType type: TypeOfFigure) -> Figure {
        switch type {
            case .square: return new FigureSquare()
            case .circle: return new FigureCircle()
            case .triangle: return new FigureTriangle()
        }
    }
}

class Figure { }

class FigureSquare: Figure, Square { }

关于ios - swift 协议(protocol) : Adding Protocol conformance to an Instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39039892/

相关文章:

ios - 在 iOS 中从后台启动 UIViewController

ios - 从容器 View 内的 View 将 View 推送到导航堆栈?

ios - 实现 UITextFieldDelegate

python - python 协议(protocol)中的泛型 - 协方差和逆变

java - 在 RFB 协议(protocol)中提交 (x,y) 位置

swift - 为什么 Swift 编译器不能推断具有关联项的协议(protocol)的返回类型?

ios - 将 "Final"NSOperation 添加到操作次数不确定的队列中

iOS 4 : video quality with AVAsset based application

ios - 在自定义 UIView 中动画化 UIBezierPath 不起作用

swift - 专门的通用协议(protocol)只能作为通用约束