审查生成的订单状态更新

来自 枚举与模式匹配
Swift 6.3.3 高级 6分钟 找出 4处问题

根据边界契约审查这段生成的订单状态更新代码。

把服务端状态应用到订单:必须保留未知状态字符串;paid 要求非空收据;失败原因属于敏感数据;分派逻辑应清楚展示完整状态映射。

swift
enum ServerStatus: String {
    case pending
    case paid
    case failed
}

enum OrderState {
    case pending
    case paid(receipt: String)
    case failed(reason: String)
    case unknown(String)
}

func apply(statusText: String, receipt: String?, reason: String?,
           to state: inout OrderState) {
    let status = ServerStatus(rawValue: statusText)!
    if case .paid = status {
        state = .paid(receipt: receipt ?? "")
    }
    if case .failed = status {
        print("failure reason:", reason ?? "none")
        state = .failed(reason: reason ?? "unknown")
    }
    if case .pending = status { state = .pending }
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误