示例工程 08-structs-enums

08-structs-enums/Sources/Ch08Kit/Properties.swift

swift · 1.7 KB

import Foundation
 
/// 计算属性、属性观察器、`lazy`、`static` 与 `CaseIterable`。
public struct Temperature: Sendable, Equatable {
    public var celsius: Double {
        didSet {
            observations += 1
        }
    }
 
    public private(set) var observations: Int = 0
 
    public init(celsius: Double) {
        self.celsius = celsius
    }
 
    /// 计算属性每次访问都重新计算,不占存储。
    public var fahrenheit: Double {
        celsius * 9 / 5 + 32
    }
 
    public var described: String {
        String(format: "%.1fC/%.1fF", celsius, fahrenheit)
    }
}
 
/// `lazy` 只在首次访问时求值,适合昂贵且可能用不到的派生数据。
public struct Report {
    public let numbers: [Int]
    public private(set) var evaluations: Int = 0
 
    public init(numbers: [Int]) {
        self.numbers = numbers
    }
 
    public lazy var total: Int = {
        evaluations += 1
        return numbers.reduce(0, +)
    }()
}
 
/// 原始值枚举 + `CaseIterable`:可以遍历所有情形,输出前排序保证确定。
public enum Priority: Int, CaseIterable, Sendable, Comparable {
    case low = 0
    case normal = 1
    case high = 2
 
    public static func < (lhs: Priority, rhs: Priority) -> Bool {
        lhs.rawValue < rhs.rawValue
    }
 
    public var label: String {
        switch self {
        case .low:
            return "low"
        case .normal:
            return "normal"
        case .high:
            return "high"
        }
    }
}
 
public enum Config {
    /// `static` 属于类型,不属于实例。
    public static let defaultPriority: Priority = .normal
    public static func describe(_ priority: Priority) -> String {
        "\(priority.label)(\(priority.rawValue))"
    }
}