Stack.swift 996 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // Stack.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2019/9/26.
  6. // Copyright © 2019 zoneland. All rights reserved.
  7. //
  8. import Foundation
  9. struct Stack<Element> {
  10. fileprivate var array: [Element] = []
  11. // 1
  12. mutating func push(_ element: Element) {
  13. // 2
  14. array.append(element)
  15. }
  16. // 1
  17. mutating func pop() -> Element? {
  18. // 2
  19. return array.popLast()
  20. }
  21. func peek() -> Element? {
  22. return array.last
  23. }
  24. var isEmpty: Bool {
  25. return array.isEmpty
  26. }
  27. var count: Int {
  28. return array.count
  29. }
  30. }
  31. // 1
  32. extension Stack: CustomStringConvertible {
  33. // 2
  34. var description: String {
  35. // 3
  36. let topDivider = "-----Stack---\n"
  37. let bottomDivider = "\n----------\n"
  38. // 4
  39. let stackElements = array.map { "\($0)" }.reversed().joined(separator: "\n")
  40. // 5
  41. return topDivider + stackElements + bottomDivider
  42. }
  43. }