Created
July 11, 2019 15:22
-
-
Save deda9/4090ab5cdd32ad507293dfbe069ec0df to your computer and use it in GitHub Desktop.
How to create LinkedList with enum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
indirect enum LinkedList<T> { | |
case value(element: T, next: LinkedList<T>) | |
case end | |
} | |
extension LinkedList: Sequence { | |
func makeIterator() -> LinkedListIterator<T> { | |
return LinkedListIterator(current: self) | |
} | |
} | |
struct LinkedListIterator<T>: IteratorProtocol { | |
var current: LinkedList<T> | |
mutating func next() -> T? { | |
switch current { | |
case . value(let element, let next): | |
self.current = next | |
return element | |
case .end: | |
return nil | |
} | |
} | |
} | |
let x3: LinkedList<Int> = .end | |
let x2: LinkedList<Int> = .value(element: 3, next: x3) | |
let x1: LinkedList<Int> = .value(element: 32, next: x2) | |
let x: LinkedList<Int> = .value(element: 23, next: x1) | |
x.forEach { | |
print($0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment