The Swift Standard Library asserts that:
drop(while:)
Returns a subsequence by skipping elements while predicate returns true and returning the remaining elements.
By using the function signature:
func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
Where predicate
is described as:
A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
My problem is that, under that description the following behavior shouldn't occur:
let test = (0...3).drop { $0 > 1 }
test.contains(0) // true
test.contains(3) // true
I don't get why you don't understand this behaviour. The documentation is pretty clear and it matches the output.
The documentation says that the method will keep skipping (dropping) elements while the predicate is true. It's like a while loop:
// not real code, for demonstration purposes only
while predicate(sequence.first) {
sequence.dropFirst()
}
And the remaining sequence is returned.
For the sequence 0...3
, it's basically [0, 1, 2, 3]
right?
Does the first element, 0, satisfy the predicate $0 > 1
? No, so the imaginary while loop breaks, nothing is dropped, so the original sequence is returned.
I think you are confusing this with maybe prefix
?
With prefix
, it will keep adding elements to a sequence while the predicate is true and return the sequence when the predicate becomes false.
let test = (0...3).prefix { $0 > 1 }
test.contains(0) // false
test.contains(3) // false