示例工程 11-generics
11-generics/Sources/Ch11Kit/Stack.swift
/// 泛型容器:只约束到需要的程度,不假设元素可比较、可哈希。
public struct Stack<Element> {
private var storage: [Element] = []
public init() {}
public init(_ elements: [Element]) {
storage = elements
}
public var isEmpty: Bool {
storage.isEmpty
}
public var count: Int {
storage.count
}
public mutating func push(_ element: Element) {
storage.append(element)
}
public mutating func pop() -> Element? {
storage.popLast()
}
public func peek() -> Element? {
storage.last
}
/// 泛型方法:变换结果类型由调用方决定。
public func map<T>(_ transform: (Element) -> T) -> Stack<T> {
Stack<T>(storage.map(transform))
}
public var elements: [Element] {
storage
}
}
/// 条件遵循:只有元素可比较时,栈才可比较。
extension Stack: Equatable where Element: Equatable {
public static func == (lhs: Stack<Element>, rhs: Stack<Element>) -> Bool {
lhs.storage == rhs.storage
}
}
extension Stack: CustomStringConvertible where Element: CustomStringConvertible {
public var description: String {
"Stack[\(storage.map(\.description).joined(separator: ", "))]"
}
}