我正在尝试了解如何在实例具有特定值的情况下向实例添加协议(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/