Created
November 8, 2023 06:43
-
-
Save tgnivekucn/60974988ed282feb91fc58a2262feefe to your computer and use it in GitHub Desktop.
The Boxed Protocol Types example
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 { | |
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 VerticalShapes: Shape { | |
var shapes: [any Shape] // boxed Shape elements by adding any before the name of a protocol | |
func draw() -> String { | |
return shapes.map { $0.draw() }.joined(separator: "\n\n") | |
} | |
} | |
let largeTriangle = Triangle(size: 5) | |
let largeSquare = Square(size: 5) | |
let vertical = VerticalShapes(shapes: [largeTriangle, largeSquare]) | |
print(vertical.draw()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment