Future of ~Escapable for Slices

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.

  1. Has there been any internal discussion within the Swift team regarding ~Escapable collection slices?
  2. 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)
  3. 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.

1 Like

I would argue that this is already the case. If you need an owning view that keeps the storage alive, use Slice. Otherwise, you should use Span.

Some API buildout and compiler improvements are needed to make doing this more pleasant, but as far as conceptual language design goes, we're already there.

3 Likes

Will Span family contain an analog of DiscontiguousSlice? Also, is there an understanding of when lifetime annotations will allow creating Array<Span<T>>, similar to how Array<Substring> is created now?

I think that's unlikely. Span family types will remain contiguous.

The issue with Array<Span> isn't lifetime annotations, it's that Array doesn't (and can't) support ~Escapable elements. For container types that can be made to support non-escapable elements, @nnnnnnnn was looking at what would be needed in the Spring, and may have some thoughts.