Skip to content

Instantly share code, notes, and snippets.

@dennisvennink
Forked from ole/headAndTail.swift
Last active January 17, 2021 09:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dennisvennink/e8b1921916d3c2f90ab52f47291145ef to your computer and use it in GitHub Desktop.
Save dennisvennink/e8b1921916d3c2f90ab52f47291145ef to your computer and use it in GitHub Desktop.
Swift challenge: Sequence.headAndTail
extension Sequence {
var headAndTail: (head: Element, tail: SubSequence)? {
var head: Element?
let tail = drop {
if head == nil {
head = $0
return true
} else {
return false
}
}
guard head != nil else {
return nil
}
return (head: head!, tail: tail)
}
}
nonConsumingTestCase: do {
let (head, tail) = [1, 2, 3, 4].headAndTail!
assert(head == 1)
assert(tail == [2, 3, 4])
assert(tail == [2, 3, 4])
}
consumingTestCase: do {
var i = 0
let sequence = AnySequence {
AnyIterator { () -> Int? in
i += 1
return i
}
}
var (head, tail) = sequence.headAndTail!
assert(head == 1)
assert(tail.prefix(3).elementsEqual([2, 3, 4]))
(head, tail) = sequence.headAndTail!
assert(head == 5)
assert(tail.prefix(3).elementsEqual([6, 7, 8]))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment