Reputation:
I'm trying to understand how to add a protocol conformance to an instance if the instance has a particular value. This is a "stupid" example of what I'm trying to understand.
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 {}
}
}
}
Upvotes: 0
Views: 272
Reputation: 1138
As of "The Swift Programming Language":
The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.
Thus you can't add protocol conformance to a specific instance.
Upvotes: 1
Reputation: 4066
I propose an alternative approach
You can use a factory method:
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 { }
Upvotes: 4