A view into a subsequence of elements of another collection.
SDK
- Xcode 7.0+
Framework
- Swift Standard Library
Declaration
Overview
A slice stores a base collection and the start and end indices of the view. It does not copy the elements from the collection into separate storage. Thus, creating a slice has O(1) complexity.
Slices Share Indices
Indices of a slice can be used interchangeably with indices of the base collection. An element of a slice is located under the same index in the slice and in the base collection, as long as neither the collection nor the slice has been mutated since the slice was created.
For example, suppose you have an array holding the number of absences from each class during a session.
You’re tasked with finding the day with the most absences in the second half of the session. To find the index of the day in question, follow these setps:
Create a slice of the
absences
array that holds the second half of the days.Use the
max(by:)
method to determine the index of the day with the most absences.Print the result using the index found in step 2 on the original
absences
array.
Here’s an implementation of those steps:
Slices Inherit Semantics
A slice inherits the value or reference semantics of its base collection. That is, if a Slice
instance is wrapped around a mutable collection that has value semantics, such as an array, mutating the original collection would trigger a copy of that collection, and not affect the base collection stored inside of the slice.
For example, if you update the last element of the absences
array from 0
to 2
, the second
slice is unchanged.
Use slices only for transient computation. A slice may hold a reference to the entire storage of a larger collection, not just to the portion it presents, even after the base collection’s lifetime ends. Long-term storage of a slice may therefore prolong the lifetime of elements that are no longer otherwise accessible, which can erroneously appear to be memory leakage.
Note
Using a Slice
instance with a mutable collection requires that the base collection’s subscript(_: Index)
setter does not invalidate indices. If mutations need to invalidate indices in your custom collection type, don’t use Slice
as its subsequence type. Instead, define your own subsequence type that takes your index invalidation requirements into account.