在 Swift 中,泛型协议不能直接用于变量。如果你想存储 不同泛型类型,可以使用 类型擦除模式(Type Erasure)。
protocol Shape {func area() -> Double }// 泛型包装类,隐藏泛型类型,让shapes
数组可以存储不同的Shape
类型。 class AnyShape<T: Shape>: Shape {private let _area: () -> Doubleinit<U: Shape>(_ shape: U) where U == T {_area = shape.area}func area() -> Double {return _area()} }struct Circle: Shape {var radius: Doublefunc area() -> Double { return .pi * radius * radius } }struct Square: Shape {var side: Doublefunc area() -> Double { return side * side } }// ✅ 允许存储不同 Shape 类型 let shapes: [AnyShape<Shape>] = [AnyShape(Circle(radius: 5)), AnyShape(Square(side: 4))]for shape in shapes {print(shape.area()) }