Hi everyone
With the recent advancements in Swift’s ownership model, specifically the introduction of ~Escapable types, we now have a robust system for compile-time lifetime control. This got me thinking about the semantic nature of collection slices such as ArraySlice and others.
- Has there been any internal discussion within the Swift team regarding
~Escapablecollection slices? - Are there active thoughts on introducing non-escapable alternatives to other transient standard library views? (e.g., Substring or sequences that shouldn't outlive their underlying storage)
- Is there ultimate goal to entirely replace the use-cases of transient slices with Span / MutableSpan for performance-critical, non-escaping code, effectively leaving ArraySlice as a legacy ARC-backed convenience type?
Documentation explicitly states:
Long-term storage of ArraySlice instances is discouraged. A slice holds a reference to the entire storage of a larger array, not just to the portion it presents, even after the original array’s lifetime ends. Long-term storage of a slice may therefore prolong the lifetime of elements that are no longer otherwise accessible, which can appear to be memory and object leakage.
From a semantic standpoint Slice behaves like a non-escapable view. It is meant to be a transient instance for local, scoped computations. However, because it was designed long before lifetime annotations existed, its memory safety relies heavily on ARC and human discipline.
If slices were designed from scratch today in Swift 6, they might be modeled as non-escapable types with lifetime tied to the base collection. This would shift the burden of safety from a passive documentation warning to a strict compile-time guarantee.
Of course making all existing slices ~Escapable is a massive source-breaking change that is completely out of the question.
Span types provide great API for collections, I wonder if there are broader plans for collection views.