示例工程 10-protocols
10-protocols/Sources/Ch10Kit/Container.swift
/// 关联类型与协议组合。
public protocol Container {
associatedtype Item
func items() -> [Item]
}
public struct IntBox: Container {
public let values: [Int]
public init(_ values: [Int]) {
self.values = values
}
public func items() -> [Int] {
values
}
}
public struct StringBox: Container {
public let values: [String]
public init(_ values: [String]) {
self.values = values
}
public func items() -> [String] {
values
}
}
public enum ContainerLab {
/// 泛型约束 + 关联类型:调用方决定 Item,函数体只依赖协议。
public static func count<C: Container>(_ container: C) -> Int {
container.items().count
}
public static func join<C: Container>(_ container: C) -> String
where C.Item == String {
container.items().joined(separator: ",")
}
}
public protocol Named {
var name: String { get }
}
public protocol Aged {
var age: Int { get }
}
public struct Person: Named, Aged {
public let name: String
public let age: Int
public init(name: String, age: Int) {
self.name = name
self.age = age
}
}
public enum CompositionLab {
/// 协议组合:参数同时满足两个协议。
public static func describe(_ value: any Named & Aged) -> String {
"\(value.name)(\(value.age))"
}
public static func names(_ values: [any Named]) -> [String] {
values.map(\.name).sorted()
}
}