示例工程 12-opaque-existential-types
12-opaque-existential-types/Sources/Ch12Kit/Shapes.swift
/// 不透明返回类型:调用方知道「某种 Shape」,但不知道具体是哪种。
public protocol Shape {
var name: String { get }
func area() -> Double
}
public struct Circle: Shape {
public let radius: Double
public init(radius: Double) {
self.radius = radius
}
public var name: String { "circle" }
public func area() -> Double {
.pi * radius * radius
}
}
public struct Square: Shape {
public let side: Double
public init(side: Double) {
self.side = side
}
public var name: String { "square" }
public func area() -> Double {
side * side
}
}
public enum OpaqueLab {
/// 返回 `some Shape`:底层类型在编译期确定,调用方不需要写具体类型。
public static func unitCircle() -> some Shape {
Circle(radius: 1)
}
/// 同一函数只能返回一种底层类型;这里固定返回 `Square`。
public static func unitSquare() -> some Shape {
Square(side: 1)
}
/// 泛型上下文里使用 `some`,保留具体类型,参与特化。
public static func doubledArea(of shape: some Shape) -> Double {
shape.area() * 2
}
}
public enum ExistentialLab {
/// 存在类型:运行期可以是任意 Shape,代价是装箱与见证表。
public static func shapes() -> [any Shape] {
[Circle(radius: 1), Square(side: 2)]
}
public static func totalArea(_ shapes: [any Shape]) -> Double {
shapes.reduce(0) { $0 + $1.area() }
}
/// 主关联类型:在存在类型上指定元素类型。
public static func countInts(_ values: any Collection<Int>) -> Int {
values.count
}
}