-
-
Save dennisvennink/e8b1921916d3c2f90ab52f47291145ef to your computer and use it in GitHub Desktop.
Swift challenge: Sequence.headAndTail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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