And I came back with a List
To get a better feel for the generator pattern employed in Swift, I created a simple linked-list. Passing a List instance to a for ... in loop will iterate through the appended values.
class Node<T> {
var value: T
var next: Node<T>!
init(_ value: T) {
self.value = value
}
}
public class List<T> {
var head: Node<T>!
var tail: Node<T>!
public var isEmpty: Bool {
return head == nil
}
public func append(value: T) {
var node = Node<T>(value)
if isEmpty {
head = node
} else {
tail.next = node
}
tail = node
}
}
extension List : SequenceType {
public func generate() -> GeneratorOf<T> {
var current = head
return GeneratorOf {
if current == nil {
return nil
}
let value = current.value
current = current.next
return value
}
}
}
Below is a simple example of how to iterate through the list using the generator.
var list = List<Int>()
for i in 0...10 {
list.append(i)
}
for i in list {
println(i)
}