Skip to content

Instantly share code, notes, and snippets.

@beccadax
Created June 12, 2014 05:06
Show Gist options
  • Save beccadax/2585b526a72aa7538c54 to your computer and use it in GitHub Desktop.
Save beccadax/2585b526a72aa7538c54 to your computer and use it in GitHub Desktop.
Implementations of first() and last() functions in Swift.
func first<S: Sequence> (seq: S) -> S.GeneratorType.Element? {
var gen = seq.generate()
return gen.next()
}
func first<S: Sequence> (seq: S, #count: Int) -> Slice<S.GeneratorType.Element> {
var gen = seq.generate()
var list = Slice<S.GeneratorType.Element>()
while list.count < count {
if let elem = gen.next() {
list.append(elem)
}
else {
break
}
}
return list
}
func last<S: Sequence> (seq: S) -> S.GeneratorType.Element? {
return reduce(seq, nil) { (_: S.GeneratorType.Element?, elem) in
return elem
}
}
func last<S: Sequence> (seq: S, #count: Int) -> Slice<S.GeneratorType.Element> {
// IIRC, .removeAtIndex(0) is faster for Slice than Array;
// if I'm wrong, you could replace Slice with Array with no change.
return reduce(seq, Slice<S.GeneratorType.Element>()) { (var list, elem) in
if list.count >= count {
list.removeAtIndex(0)
}
list.append(elem)
return list
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment