Skip to content

Instantly share code, notes, and snippets.

@JadenGeller JadenGeller/Finite.swift
Last active Aug 29, 2015

Embed
What would you like to do?
Swift Finite Sequence
/*
* Allows you to limit the count of a sequence
*/
extension SequenceType {
func take(count: Int) -> FiniteSequence<Generator.Element> {
return FiniteSequence(backing: AnySequence(self), count: count)
}
}
struct FiniteSequence<T> : SequenceType {
private let backing: AnySequence<T>
private let count: Int
func generate() -> FiniteGenerator<T> {
return FiniteGenerator(backing: backing.generate(), countRemaining: count)
}
}
struct FiniteGenerator<T> : GeneratorType {
private var backing: AnyGenerator<T>
private(set) var countRemaining: Int
mutating func next() -> T? {
return countRemaining-- > 0 ? backing.next() : nil
}
}
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n in arr.take(4) {
println(n) // -> 1
} // -> 2
// -> 3
// -> 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.