Code
swift
import Foundation
protocol Drawable {
func draw() -> String
var area: Double { get }
}
// Conforming type
struct Circle: Drawable {
let radius: Double
var area: Double { Double.pi * radius * radius }
func draw() -> String { "Circle r=\(radius)" }
}
struct Square: Drawable {
let side: Double
var area: Double { side * side }
func draw() -> String { "Square s=\(side)" }
}
// Protocol as existential type
func describe(_ shapes: [any Drawable]) {
for s in shapes {
print("\(s.draw()) area=\(s.area)")
}
}
describe([Circle(radius: 2), Square(side: 3)])
// Protocol extension with default behavior
extension Drawable {
func describe() -> String { "\(draw()) area=\(area)" }
}
let c = Circle(radius: 1)
print(c.describe())
// Protocol with associated type
protocol Container {
associatedtype Item
var count: Int { get }
mutating func append(_ item: Item)
subscript(i: Int) -> Item { get }
}