示例工程 05-control-flow-pattern-matching

05-control-flow-pattern-matching/Sources/Ch05Kit/Shape.swift

swift · 2.1 KB

import Foundation
 
/// 关联值 + `where` 子句:几何形状的面积计算,覆盖公开枚举的每种情形。
public enum Shape: Sendable, Equatable {
    case circle(radius: Double)
    case rectangle(width: Double, height: Double)
    case triangle(base: Double, height: Double)
 
    public var area: Double {
        switch self {
        case .circle(let radius) where radius > 0:
            return .pi * radius * radius
        case .circle:
            return 0
        case .rectangle(let width, let height) where width > 0 && height > 0:
            return width * height
        case .rectangle:
            return 0
        case .triangle(let base, let height) where base > 0 && height > 0:
            return base * height / 2
        case .triangle:
            return 0
        }
    }
 
    public var name: String {
        switch self {
        case .circle:
            return "circle"
        case .rectangle:
            return "rectangle"
        case .triangle:
            return "triangle"
        }
    }
}
 
/// 区间模式与元组模式:`switch` 必须穷尽,编译器会检查。
public enum RangeLab {
    public static func grade(_ score: Int) -> String {
        switch score {
        case ..<0:
            return "invalid"
        case 0..<60:
            return "F"
        case 60..<70:
            return "D"
        case 70..<80:
            return "C"
        case 80..<90:
            return "B"
        case 90...100:
            return "A"
        default:
            return "invalid"
        }
    }
 
    public static func quadrant(_ point: (x: Int, y: Int)) -> String {
        switch point {
        case (0, 0):
            return "origin"
        case (let x, 0):
            return "x-axis(\(x))"
        case (0, let y):
            return "y-axis(\(y))"
        case (let x, let y) where x > 0 && y > 0:
            return "I"
        case (let x, let y) where x < 0 && y > 0:
            return "II"
        case (let x, let y) where x < 0 && y < 0:
            return "III"
        default:
            return "IV"
        }
    }
}