示例工程 05-control-flow-pattern-matching

05-control-flow-pattern-matching/Sources/Ch05Kit/LoopLab.swift

swift · 1.5 KB

/// 循环控制:`for ... where`、带标签的 `break`、`repeat-while`。
public enum LoopLab {
    public static func sumEven(_ values: [Int]) -> Int {
        var total = 0
        for value in values where value % 2 == 0 {
            total += value
        }
        return total
    }
 
    /// 找到第一对下标不同、和等于 target 的元素;找不到返回 nil。
    public static func firstPair(_ values: [Int], target: Int) -> (Int, Int)? {
        var result: (Int, Int)?
        outer: for i in values.indices {
            for j in values.indices where j > i {
                if values[i] + values[j] == target {
                    result = (values[i], values[j])
                    break outer
                }
            }
        }
        return result
    }
 
    /// `repeat-while` 至少执行一次;这里模拟「先取一位数字再判断」。
    public static func digitsReversed(_ value: Int) -> [Int] {
        var remaining = abs(value)
        var digits: [Int] = []
        repeat {
            digits.append(remaining % 10)
            remaining /= 10
        } while remaining > 0
        return digits
    }
 
    /// 带标签的 `continue`:跳过当前行,而不是只跳过内层。
    public static func nonZeroRows(_ rows: [[Int]]) -> [[Int]] {
        var kept: [[Int]] = []
        rowLoop: for row in rows {
            for value in row where value == 0 {
                continue rowLoop
            }
            kept.append(row)
        }
        return kept
    }
}