示例工程 10-protocols

10-protocols/Sources/Ch10Kit/ShapeProtocol.swift

swift · 1.2 KB

/// 协议作为类型:不同具体类型可以放进同一个存在类型数组。
public protocol Shape {
    var name: String { get }
    func area() -> Double
}
 
public struct Circle: Shape {
    public let name = "circle"
    public let radius: Double
 
    public init(radius: Double) {
        self.radius = radius
    }
 
    public func area() -> Double {
        .pi * radius * radius
    }
}
 
public struct Rectangle: Shape {
    public let name = "rectangle"
    public let width: Double
    public let height: Double
 
    public init(width: Double, height: Double) {
        self.width = width
        self.height = height
    }
 
    public func area() -> Double {
        width * height
    }
}
 
public enum ShapeLab {
    public static func names(_ shapes: [any Shape]) -> [String] {
        shapes.map(\.name).sorted()
    }
 
    public static func totalArea(_ shapes: [any Shape]) -> Double {
        shapes.reduce(0) { $0 + $1.area() }
    }
}
 
/// 给系统类型加能力:`String` 也能遵循自定义协议。
public protocol Describable {
    var shortDescription: String { get }
}
 
extension String: Describable {
    public var shortDescription: String {
        count <= 3 ? self : "\(prefix(3))…"
    }
}