Last active
September 20, 2017 11:41
-
-
Save nyg/7b69d0a34e0927a42a5514b88d1cfbe1 to your computer and use it in GitHub Desktop.
Implementing Sequence & IteratorProtocol, Swift 3
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
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