Last active
November 8, 2023 06:29
-
-
Save tgnivekucn/5a4a9212843a5308e42a179efdd25e9e to your computer and use it in GitHub Desktop.
Opaque type decided by function implementation
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
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