Last active
October 24, 2017 06:57
-
-
Save dakeshi/ede1ff0ee5ff192b0528775605c55d2a to your computer and use it in GitHub Desktop.
Fix LinkedList demo code in academy.realm.io(https://academy.realm.io/posts/try-swift-soroush-khanlou-sequence-collection/)
This file contains hidden or 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
/*: | |
* [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