示例工程 08-structs-enums

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

swift · 1.5 KB

/// 用枚举建模下载状态:每种状态携带自己的数据,`switch` 强制穷尽。
public enum DownloadState: Sendable, Equatable {
    case idle
    case loading(progress: Double)
    case success(bytes: Int)
    case failed(reason: String)
 
    public var isTerminal: Bool {
        switch self {
        case .idle, .loading:
            return false
        case .success, .failed:
            return true
        }
    }
 
    public var description: String {
        switch self {
        case .idle:
            return "idle"
        case .loading(let progress):
            return "loading(\(progress))"
        case .success(let bytes):
            return "success(\(bytes))"
        case .failed(let reason):
            return "failed(\(reason))"
        }
    }
}
 
/// 值类型持有状态;`mutating` 方法等价于 `inout self`。
public struct Download: Sendable, Equatable {
    public private(set) var state: DownloadState = .idle
 
    public init() {}
 
    public mutating func start() {
        guard case .idle = state else { return }
        state = .loading(progress: 0)
    }
 
    public mutating func advance(to progress: Double) {
        guard case .loading = state else { return }
        state = .loading(progress: min(max(progress, 0), 1))
    }
 
    public mutating func finish(bytes: Int) {
        guard case .loading = state else { return }
        state = .success(bytes: bytes)
    }
 
    public mutating func fail(reason: String) {
        guard !state.isTerminal else { return }
        state = .failed(reason: reason)
    }
}