Suppose I have requirement to draw a shape. The shape will be decided by backend server. I have following code:
enum ShapeType {
case circle
case rectangle
}
protocol Shape {
var type: ShapeType { get }
func render()
}
struct Circle: Shape {
let type: ShapeType = .circle
func render() {
print("Draw Circle")
}
}
struct Rectangle: Shape {
let type: ShapeType = .rectangle
func render() {
print("Draw Rectangle")
}
}
my current logic to select a shape to draw is:
if serverShapeString == "Circle" {
let circleShape: Shape = Circle()
circleShape.render()
} else {
let rectangleShape: Shape = Rectangle()
rectangleShape.render()
}
I have written the protocol and the enum. If any new shape comes I will write separate class for it but still don;t get how to avoid if else based on the serverShapeString. I have to avoid that if else because it keeps on increasing as we have more shapes.