示例工程 04-collections-cow
04-collections-cow/Sources/Ch04Kit/CollectionLab.swift
/// 集合的确定性输出与排序:`Set`/`Dictionary` 的迭代顺序不稳定,打印前必须排序。
public enum CollectionLab {
public static func sortedSet(_ values: [Int]) -> [Int] {
Set(values).sorted()
}
public static func sortedKeys(_ pairs: [(String, Int)]) -> [String] {
var dictionary: [String: Int] = [:]
for (key, value) in pairs {
dictionary[key] = value
}
return dictionary.keys.sorted()
}
public static func sortedEntries(_ pairs: [(String, Int)]) -> [String] {
var dictionary: [String: Int] = [:]
for (key, value) in pairs {
dictionary[key] = value
}
return dictionary.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }
}
/// 预分配容量后,`capacity` 至少达到请求值。
public static func reserveCapacityProbe(_ requested: Int) -> (reserved: Int, enough: Bool) {
var values: [Int] = []
values.reserveCapacity(requested)
return (values.capacity, values.capacity >= requested)
}
}
/// 排序的确定性来自显式的次级比较,而不是依赖「稳定排序」的实现细节。
public struct Score: Sendable, Equatable {
public let name: String
public let points: Int
public init(name: String, points: Int) {
self.name = name
self.points = points
}
}
public enum SortingLab {
/// 先按分数降序,再按名字升序;同分时顺序唯一。
public static func ranked(_ scores: [Score]) -> [Score] {
scores.sorted {
if $0.points != $1.points { return $0.points > $1.points }
return $0.name < $1.name
}
}
public static func describe(_ scores: [Score]) -> [String] {
ranked(scores).map { "\($0.name):\($0.points)" }
}
}