Skip to content

Instantly share code, notes, and snippets.

@imaximix
Created November 1, 2016 14:25
Show Gist options
  • Save imaximix/ea816fcac11eff43ffa663fe4a86cd9d to your computer and use it in GitHub Desktop.
Save imaximix/ea816fcac11eff43ffa663fe4a86cd9d to your computer and use it in GitHub Desktop.
func cycle<A>(coll: [A]) -> AnyIterator<A> {
var cursor = 0
let infiniteItems = AnyIterator { () -> A in
let itemToReturn = coll[cursor]
cursor += 1
if (cursor > coll.count - 1) {
cursor = 0
}
return itemToReturn
}
return infiniteItems
}
let ticTac = cycle(["tic", "tac"])
print(ticTac.next()) // "tic"
print(ticTac.next()) // "tac"
print(ticTac.next()) // "tic"
print(ticTac.next()) // "tac"
print(ticTac.next()) // "tic"
func take<A>(count: Int, coll: AnyIterator<A>) -> [A] {
var returnValue: [A] = []
for _ in 1...count {
returnValue.append(coll.next()!)
}
return returnValue
}
let ticTac = cycle(["tic", "tac"])
print(take(3, ticTac)) // ["tic", "tac" ,"tic"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment