Skip to content

Instantly share code, notes, and snippets.

@dakeshi
Last active October 24, 2017 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dakeshi/ede1ff0ee5ff192b0528775605c55d2a to your computer and use it in GitHub Desktop.
Save dakeshi/ede1ff0ee5ff192b0528775605c55d2a to your computer and use it in GitHub Desktop.
/*:
* [How to make custom iterator](https://academy.realm.io/posts/try-swift-soroush-khanlou-sequence-collection/)
* [Implementation of a LinkedList using enum](https://github.com/apple/swift/blob/master/stdlib/public/core/Sequence.swift)
*/
import Foundation
indirect enum LinkedListNode<T> {
case value(element: T, next: LinkedListNode<T>)
case end
}
//extension LinkedListNode: Sequence {
// func makeIterator() -> LinkedListIterator<T> {
// return LinkedListIterator(current: self)
// }
//}
// You can use a default implementation for makeIterator()
struct LinkedListIterator<T>: Sequence, IteratorProtocol {
var current: LinkedListNode<T>
mutating func next() -> T? {
switch current {
case let .value(element, next):
current = next
return element
case .end:
return nil
}
}
}
// create LinkedListNode
let second = LinkedListNode.value(element: "C", next: LinkedListNode.end)
let first = LinkedListNode.value(element: "B", next: second)
let head = LinkedListNode.value(element: "A", next: first)
// use `var` instead of `let`.
// because iterator.next() is a mutating function.
var iterator = LinkedListIterator<String>(current: head)
while let value = iterator.next() {
print(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment