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/5a4a9212843a5308e42a179efdd25e9e to your computer and use it in GitHub Desktop.
Save tgnivekucn/5a4a9212843a5308e42a179efdd25e9e to your computer and use it in GitHub Desktop.
Opaque type decided by function implementation
public 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()
}
}
public func makeTrapezoid() -> some Shape {
let top = Square(size: 3) // Triangle(size: 2)
let middle = Square(size: 2)
let bottom = FlippedShape(shape: top)
let trapezoid = JoinedShape(top: top,
bottom: JoinedShape(top: middle, bottom: bottom)
)
print(trapezoid.self) // the type is decided by what types you used to create JoinedShape
return trapezoid
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment