Standard Library Protocols
✅ (structs/enums whose members are Equatable) Set/Dictionary keys (hash(into:)) <, enables sort(), min(), max()
✅ for enums without associated values (or with Comparable payloads) Stable id (SwiftUI lists)
CustomStringConvertible / CustomDebugStringConvertible description / debugDescription Codable (Encodable & Decodable) ✅ (enums without associated values) ✅ (enums with raw types)
Safe to share across concurrency domains Implicit for many value types
Sequence, IteratorProtocol, Collection, BidirectionalCollection, RandomAccessCollection, MutableCollection, RangeReplaceableCollection
ExpressibleByStringLiteral, ...IntegerLiteral, ...ArrayLiteral, ...DictionaryLiteral, ...NilLiteral Error, LocalizedError
Numeric, BinaryInteger, FloatingPoint, AdditiveArithmetic stride, ranges
struct Version: Comparable, Hashable, CustomStringConvertible, ExpressibleByStringLiteral {
let major: Int, minor: Int, patch: Int
init(stringLiteral value: String) {
let parts = value.split(separator: ".").compactMap { Int($0) }
(major, minor, patch) = (parts[0], parts[safe: 1] ?? 0, parts[safe: 2] ?? 0)
}
static func < (lhs: Version, rhs: Version) -> Bool {
(lhs.major, lhs.minor, lhs.patch) < (rhs.major, rhs.minor, rhs.patch)
}
var description: String { "\(major).\(minor).\(patch)" }
}
let versions: [Version] = ["1.10.0", "1.2.3", "1.2.10"]
print(versions.sorted()) // [1.2.3, 1.2.10, 1.10.0]
let set: Set<Version> = ["1.0.0", "1.0.0"] // one element (Hashable synthesized)
struct Countdown: Sequence, IteratorProtocol {
var count: Int
mutating func next() -> Int? {
guard count > 0 else { return nil }
defer { count -= 1 }
return count
}
}
for n in Countdown(count: 3) { print(n) } // 3 2 1
Countdown(count: 5).map { $0 * 2 }