示例工程 12-opaque-existential-types
12-opaque-existential-types/Tests/Ch12KitTests/OpaqueTests.swift
import Testing
@testable import Ch12Kit
@Suite("some 与 any")
struct OpaqueTests {
@Test func opaqueTypeHidesConcreteNameButKeepsBehavior() {
let shape = OpaqueLab.unitCircle()
#expect(shape.name == "circle")
#expect(abs(shape.area() - Double.pi) < 1e-12)
#expect(String(describing: type(of: shape)) == "Circle")
}
@Test func opaqueTypeWorksAsGenericArgument() {
let shape = OpaqueLab.unitCircle()
#expect(abs(OpaqueLab.doubledArea(of: shape) - 2 * Double.pi) < 1e-12)
}
@Test func sameFunctionAlwaysReturnsSameUnderlyingType() {
#expect(String(describing: type(of: OpaqueLab.unitSquare())) == "Square")
}
@Test func existentialArrayHoldsHeterogeneousShapes() {
let shapes = ExistentialLab.shapes()
#expect(shapes.count == 2)
#expect(ExistentialLab.totalArea(shapes) == Double.pi + 4)
}
@Test func primaryAssociatedTypeConstrainsElement() {
#expect(ExistentialLab.countInts([1, 2, 3]) == 3)
#expect(ExistentialLab.countInts(Set([1, 2, 3])) == 3)
}
@Test func existentialIsLargerThanConcreteType() {
#expect(MemoryLayout<any Shape>.size > MemoryLayout<Circle>.size)
#expect(MemoryLayout<Circle>.size == 8)
}
}