Skip to content

Instantly share code, notes, and snippets.

@BasThomas
Last active February 26, 2019 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BasThomas/082b1202f05e341ef6519f116b003108 to your computer and use it in GitHub Desktop.
Save BasThomas/082b1202f05e341ef6519f116b003108 to your computer and use it in GitHub Desktop.
struct Solution<Problem>: Collection {
struct Step<T> {
let step: T
}
let steps: [Step<Problem>]
var input: Step<Problem> {
return steps.first! // safe, as steps will guaranteed to be larger than 0.
}
var output: Step<Problem> {
return steps.last! // safe, as steps will guaranteed to be larger than 0.
}
init(steps: [Step<Problem>]) {
precondition(steps.count > 0, "Solution must contain at least one step.")
self.steps = steps
}
init(steps: Step<Problem>...) {
self.init(steps: steps)
}
var startIndex: Int {
return steps.startIndex
}
var endIndex: Int {
return steps.endIndex
}
subscript(i: Int) -> Step<Problem> {
return steps[i]
}
func index(after i: Int) -> Int {
return steps.index(after: i)
}
}
struct Solution<Problem>: Sequence, IteratorProtocol {
struct Step<T> {
let step: T
}
let steps: [Step<Problem>]
var input: Step<Problem> {
return steps.first! // safe, as steps will guaranteed to be larger than 0.
}
var output: Step<Problem> {
return steps.last! // safe, as steps will guaranteed to be larger than 0.
}
init(steps: [Step<Problem>]) {
precondition(steps.count > 0, "Solution must contain at least one step.")
self.steps = steps
}
init(steps: Step<Problem>...) {
self.init(steps: steps)
}
private var _index: Int? = nil
mutating func next() -> Step<Problem>? {
// 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
Copy link
Author

let solution = Solution<Int>(steps: Solution.Step(step: 1), Solution.Step(step: 2), Solution.Step(step: 3))

for step in solution {
  print(step)
}

// Step<Int>(step: 1)
// Step<Int>(step: 2)
// Step<Int>(step: 3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment