Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgnivekucn/2394ee4b6753b01ef3d7a26c2f35c1f9 to your computer and use it in GitHub Desktop.
Save tgnivekucn/2394ee4b6753b01ef3d7a26c2f35c1f9 to your computer and use it in GitHub Desktop.
The Problem That Opaque Types Solve
protocol Shape {
associatedtype T
func draw() -> String
}
struct Triangle: Shape {
typealias T = Int
var size: Int
func draw() -> String {
var result: [String] = []
for length in 1...size {
result.append(String(repeating: "*", count: length))
}
return result.joined(separator: "\n")
}
}
struct Square: Shape {
typealias T = Int
var size: Int
func draw() -> String {
let line = String(repeating: "*", count: size)
let result = Array<String>(repeating: line, count: size)
return result.joined(separator: "\n")
}
}
struct FlippedShape<T: Shape>: Shape {
var shape: T
func draw() -> String {
let lines = shape.draw().split(separator: "\n")
return lines.reversed().joined(separator: "\n")
}
}
struct JoinedShape<T: Shape, U: Shape>: Shape {
var top: T
var bottom: U
func draw() -> String {
return top.draw() + "\n" + bottom.draw()
}
}
func makeTrapezoid() -> some Shape {
let top = Triangle(size: 2)
let middle = Square(size: 2)
let bottom = FlippedShape(shape: top)
let trapezoid = JoinedShape(top: top,
bottom: JoinedShape(top: middle, bottom: bottom))
return trapezoid
}
// Below is client
let myShape = makeTrapezoid()
let drawResult = myShape.draw()
print(drawResult)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment