Created
November 8, 2023 05:57
-
-
Save tgnivekucn/2394ee4b6753b01ef3d7a26c2f35c1f9 to your computer and use it in GitHub Desktop.
The Problem That Opaque Types Solve
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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