{{ message }}

Instantly share code, notes, and snippets.

# BasThomas/Solution+Collection.swift

Last active Feb 26, 2019
 struct Solution: Collection { struct Step { let step: T } let steps: [Step] var input: Step { return steps.first! // safe, as steps will guaranteed to be larger than 0. } var output: Step { return steps.last! // safe, as steps will guaranteed to be larger than 0. } init(steps: [Step]) { precondition(steps.count > 0, "Solution must contain at least one step.") self.steps = steps } init(steps: Step...) { self.init(steps: steps) } var startIndex: Int { return steps.startIndex } var endIndex: Int { return steps.endIndex } subscript(i: Int) -> Step { return steps[i] } func index(after i: Int) -> Int { return steps.index(after: i) } }
 struct Solution: Sequence, IteratorProtocol { struct Step { let step: T } let steps: [Step] var input: Step { return steps.first! // safe, as steps will guaranteed to be larger than 0. } var output: Step { return steps.last! // safe, as steps will guaranteed to be larger than 0. } init(steps: [Step]) { precondition(steps.count > 0, "Solution must contain at least one step.") self.steps = steps } init(steps: Step...) { self.init(steps: steps) } private var _index: Int? = nil mutating func next() -> Step? { // we're counting up (looping though the steps array), so begin at _index 0. if _index == nil { _index = 0 } // shadow _index so we do not have to deal with its optionality // this is also why the "other" index is underscored. var index = _index! if index < steps.count { // always move the _index forward after we can return a step defer { _index! += 1 } return steps[index] } else { // when we're done, reset the _index to nil. _index = nil return nil } } }

### BasThomas commented Feb 24, 2019

 ```let solution = Solution(steps: Solution.Step(step: 1), Solution.Step(step: 2), Solution.Step(step: 3)) for step in solution { print(step) } // Step(step: 1) // Step(step: 2) // Step(step: 3)```