Skip to content

Instantly share code, notes, and snippets.

@below
Created January 15, 2021 13:00
Show Gist options
  • Save below/63b58aae2ad162e801967c9d42d9052d to your computer and use it in GitHub Desktop.
Save below/63b58aae2ad162e801967c9d42d9052d to your computer and use it in GitHub Desktop.
// Do you like my endless iterator?
struct EndlessIterator {
var baseIterator: String.Iterator?
var start: String
init(_ start: String) {
self.start = start
}
mutating func next() -> Character {
var item = baseIterator?.next()
if item == nil {
baseIterator = start.makeIterator()
item = baseIterator?.next()
}
guard let result = item else {
fatalError("Endless iterator ended")
}
return result
}
}
@mrcljx
Copy link

mrcljx commented Jan 16, 2021

func loopingForever<S: Sequence>(
    over sequence: S
) -> AnySequence<S.Element> {
    let repeating = AnyIterator { sequence }
    let result = repeating.lazy.flatMap { $0 }
    return AnySequence(result)
}

let example = loopingForever(over: "abc")
print(Array(example.prefix(7)))
// ["a", "b", "c", "a", "b", "c", "a"]

Source

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