示例工程 02-values-variables-types
02-values-variables-types/Sources/Ch02Kit/TupleLab.swift
/// 元组是值不是对象:可以带标签、可以解构,但不能加方法、不能遵循自定义协议。
public enum TupleLab {
public static let labeledPoint = (x: 3, y: 4)
public static func swapped<T>(_ pair: (T, T)) -> (T, T) {
(pair.1, pair.0)
}
/// 元组标签只影响访问名,不影响类型:`(x: Int, y: Int)` 与 `(Int, Int)` 是同一类型。
public static func distanceSquared(_ point: (x: Int, y: Int)) -> Int {
point.x * point.x + point.y * point.y
}
public static func decompose(_ point: (x: Int, y: Int)) -> String {
let (x, y) = point
return "x=\(x), y=\(y)"
}
/// 多返回值就是元组;调用方可以用 `_` 丢弃不关心的分量。
public static func minMax(_ values: [Int]) -> (min: Int, max: Int)? {
guard let first = values.first else { return nil }
return values.dropFirst().reduce((first, first)) { partial, value in
(Swift.min(partial.0, value), Swift.max(partial.1, value))
}
}
}
/// `typealias` 只是别名,不产生新类型;类型安全要靠新类型(struct wrapper)实现。
public typealias UserID = Int
public typealias Measurement = (value: Double, unit: String)