示例工程 10-protocols
10-protocols/Tests/Ch10KitTests/ShapeTests.swift
import Testing
@testable import Ch10Kit
@Suite("协议与存在类型")
struct ShapeTests {
@Test func areaIsComputedPerConcreteType() {
#expect(abs(Circle(radius: 1).area() - Double.pi) < 1e-12)
#expect(Rectangle(width: 3, height: 4).area() == 12)
}
@Test func existentialArrayKeepsConcreteBehavior() {
let shapes: [any Shape] = [Circle(radius: 2), Rectangle(width: 3, height: 4)]
#expect(ShapeLab.names(shapes) == ["circle", "rectangle"])
#expect(abs(ShapeLab.totalArea(shapes) - (4 * Double.pi + 12)) < 1e-12)
}
@Test func systemTypeCanAdoptLocalProtocol() {
#expect("abcdef".shortDescription == "abc…")
#expect("ab".shortDescription == "ab")
#expect("".shortDescription == "")
}
}