Skip to content

Instantly share code, notes, and snippets.

@tgnivekucn
Created November 8, 2023 06:43
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/60974988ed282feb91fc58a2262feefe to your computer and use it in GitHub Desktop.
Save tgnivekucn/60974988ed282feb91fc58a2262feefe to your computer and use it in GitHub Desktop.
The Boxed Protocol Types example
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