It just occurred to me that when working with subsequences in Swift,
func suffix(from: Int)
seems to be identical to just dropFirst(_:)
(Obviously, you just change the input value from say "3" to "7" in the case of an array of length "10".)
Just to repeat that. So: of course, for an array of say length ten. What I mean is func suffix(from: Int)
with "2" would be the same as dropFirst(_:)
with "8", for example.
Similarly upTo
/ through
seem to be identical to dropLast(_:)
Other than convenience is there any difference at all?
(Perhaps in error conditions, performance, or?)
I was wondering whether, in fact, inside Swift one or the other is just implemented by calling the other?
They are completely different.
suffix(from:)
Collection
protocol.Subsequence
from a given startingIndex
.dropFirst(_:)
Sequence
protocol.SubSequence
with a given maximum number of elements removed from the head of the sequence.*As with all protocol requirement documented time complexities, it's possible for the conforming type to have an implementation with a lower time complexity. For example, a
RandomAccessCollection
'sdropFirst(_:)
method will run in O(1) time.However, when it comes to
Array
, these methods just happen to behave identically (except for the handling of out of range inputs).This is because
Array
has anIndex
of typeInt
that starts from0
and sequentially counts up toarray.count - 1
, therefore meaning that a subsequence with the firstn
elements dropped is the same subsequence that starts from the indexn
.Also because
Array
is aRandomAccessCollection
, both methods will run in O(1) time.Biggest difference IMO is that
dropFirst()
doesn't expose your code to out-of-range index errors. So you can safely use either form ofdropFirst
on an empty array, while theprefix
/suffix
methods can crash on an empty array or with out-of-range parameters.So
dropFirst()
FTW if you'd prefer an empty array result when you specify more elements than are available rather than a crash, or if you don't want / need to check to make sure your the index you'll be using is less than thearray.count
, etc.Conceptually, I think this makes sense for the operation as named, considering that
first
is an optional-typed property that returns the first element if it exists. SayingdropFirst(3)
means "remove the maybe-present first element if it exists, and do so three times"You're right that they're connected, but yes there is a difference. From the docs:
versus
In the first example, suffix(2) returns only the last two elements, whereas dropFirst(2) returns all but the first two elements. Similarly, they behave differently wrt. arguments longer than the sequence is long. (Additionally, suffix will only work on finite sequences.)
Likewise with prefix and dropLast. Another way of thinking about it, for a sequence of length n, prefix(k) == dropLast(n-k), where k <= n.