示例工程 06-functions-closures

06-functions-closures/Sources/Ch06Kit/LabelLab.swift

swift · 1.2 KB

/// 参数标签与形参名:调用点看到的是标签,函数体看到的是形参名。
public enum LabelLab {
    /// 外部标签 `name`/`age`,内部形参同名;省略 `age` 时用默认值。
    public static func makeUser(name: String, age: Int = 18) -> String {
        "\(name)(\(age))"
    }
 
    /// 用 `_` 省略外部标签,调用点更像数学函数。
    public static func square(_ value: Int) -> Int {
        value * value
    }
 
    /// 两个标签不同:外部 `from`/`to`,内部 `start`/`end`。
    public static func distance(from start: (Int, Int), to end: (Int, Int)) -> Int {
        let dx = end.0 - start.0
        let dy = end.1 - start.1
        return dx * dx + dy * dy
    }
 
    /// 可变参数:调用方可以传任意个整数。
    public static func total(_ values: Int...) -> Int {
        values.reduce(0, +)
    }
}
 
/// `inout` 参数:函数可以修改调用方的变量,但访问必须独占。
public enum InoutLab {
    public static func swapValues<T>(_ lhs: inout T, _ rhs: inout T) {
        let temporary = lhs
        lhs = rhs
        rhs = temporary
    }
 
    public static func increment(_ value: inout Int, by step: Int) {
        value += step
    }
}