Skip to content

Instantly share code, notes, and snippets.

@nyg
Last active September 20, 2017 11:41
Show Gist options
  • Save nyg/7b69d0a34e0927a42a5514b88d1cfbe1 to your computer and use it in GitHub Desktop.
Save nyg/7b69d0a34e0927a42a5514b88d1cfbe1 to your computer and use it in GitHub Desktop.
Implementing Sequence & IteratorProtocol, Swift 3
import Foundation
class Cell {
var name: String
init(_ name: String) {
self.name = name
}
}
class Row: Sequence, IteratorProtocol {
typealias Element = Cell
var iteratorIndex: Int = 0
var cells = [Cell]()
init(cellNames: String...) {
for name in cellNames {
cells.append(Cell(name))
}
}
func next() -> Cell? {
if iteratorIndex >= cells.count {
return nil
}
defer {
iteratorIndex += 1
}
return cells[iteratorIndex]
}
func makeIterator() -> Row {
self.iteratorIndex = 0
return self
}
}
let row = Row(cellNames: "one", "two", "three")
for cell in row {
print(cell.name)
}
for (index, cell) in row.enumerated() {
print("[\(index), \(cell.name)]")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment