/// 泛型容器:只约束到需要的程度,不假设元素可比较、可哈希。 public struct Stack { 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(_ transform: (Element) -> T) -> Stack { Stack(storage.map(transform)) } public var elements: [Element] { storage } } /// 条件遵循:只有元素可比较时,栈才可比较。 extension Stack: Equatable where Element: Equatable { public static func == (lhs: Stack, rhs: Stack) -> Bool { lhs.storage == rhs.storage } } extension Stack: CustomStringConvertible where Element: CustomStringConvertible { public var description: String { "Stack[\(storage.map(\.description).joined(separator: ", "))]" } }