/* * definition */ indirect enum LinkedList : Sequence { case end case node(value: T, next: LinkedList) init() { self = .end } init(value: T) { self = .node(value: value, next: .end) } mutating func push(_ item: T) { self = .node(value: item, next: self) } mutating func pop() -> T? { switch self { case .end: return nil case .node(let value, let next): self = next return value } } func makeIterator() -> LinkedList.Iterator { return Iterator(self) } struct Iterator : IteratorProtocol { typealias Element = T private var list: LinkedList init(_ list: LinkedList) { self.list = list } mutating func next() -> LinkedList.Iterator.Element? { switch self.list { case .end: return nil case .node(let value, let nextList): self.list = nextList return value } } } } /* * usages */ var linked = LinkedList(value: "first") linked.push("second") print(linked) for v in linked { print(v) // second, first } if let value = linked.pop() { print(value) // second } for v in linked { print(v) // first }