Shadow Of Shadow Of - 6 months ago 39
Swift Question

Why SequenceType.dropFirst(_:) return Self.SubSequence instead of Self?

Trying to understand


protocol SequenceType {
associatedtype SubSequence
@warn_unused_result func dropFirst(_ n: Int) -> Self.SubSequence
/* ... */

Why we ever need
associatedtype SubSequence
, why not


This is done for increased flexibility. Allowing a class conforming to SequenceType protocol to define a different class to represent its subsequence lets implementers construct lightweight classes that present a view into original sequence without making a copy, while preserving the ability to reuse the same sequence type as Subsequence.

Consider an implementation of a tree set collection that keeps its elements sorted. An implementation of dropFirst has an option of returning a "subtree" collection that is linked to the original tree, but has a different starting node. An implementation of such subtree could be extremely lightweight - you would need the same amount of space regardless of the size of the tree, an O(1). In contrast, binding implementers to the same tree class would force them to make a copy of the subtree, which is O(n).