示例工程 02-values-variables-types

02-values-variables-types/Sources/Ch02Kit/Termination.swift

swift · 1.0 KB

/// `Never` 表示「不会正常返回」:`fatalError` 与 `preconditionFailure` 的返回类型就是它。
public enum Termination {
    /// 分类非负整数;负数分支在这里直接终止,帮助编译器做穷尽性判断。
    public static func describeNonNegative(_ value: Int) -> String {
        switch value {
        case 0:
            return "zero"
        case let positive where positive > 0:
            return "positive(\(positive))"
        default:
            fatalError("调用方违约:期望非负数,实际 \(value)")
        }
    }
 
    /// 返回 `Never` 的函数可以出现在任何期望类型的表达式位置。
    public static func unreachable(_ message: String) -> Never {
        fatalError(message)
    }
}
 
/// 变量与常量:`let` 不可重新赋值,`var` 可以;两者都是编译期检查,没有运行期开销。
public enum Counter {
    public static func increment(_ value: Int, by step: Int = 1) -> Int {
        var current = value
        current += step
        return current
    }
}