A slice of an
- Xcode 6.3+
- Swift Standard Library
Array type makes it fast and efficient for you to perform operations on sections of a larger array. Instead of copying over the elements of a slice to new storage, an
Array instance presents a view onto the storage of a larger array. And because
Array presents the same interface as
Array, you can generally perform the same operations on a slice as you could on the original array.
For more information about using arrays, see
Contiguous, with which
Array shares most properties and methods.
Slices Are Views onto Arrays
For example, suppose you have an array holding the number of absences from each class during a session.
You want to compare the absences in the first half of the session with those in the second half. To do so, start by creating two slices of the
second slices allocate any new storage of their own. Instead, each presents a view onto the storage of the
You can call any method on the slices that you might have called on the
absences array. To learn which half had more absences, use the
reduce(_: method to calculate each sum.
Slices Maintain Indices
Contiguous, the starting index for an
Array instance isn’t always zero. Slices maintain the same indices of the larger array for the same elements, so the starting index of a slice depends on how it was created, letting you perform index-based operations on either a full array or a slice.
Sharing indices between collections and their subsequences is an important part of the design of Swift’s collection algorithms. Suppose you are tasked with finding the first two days with absences in the session. To find the indices of the two days in question, follow these steps:
index(where:)to find the index of the first element in the
absencesarray that is greater than zero.
Create a slice of the
absencesarray starting after the index found in step 1.
index(where:)again, this time on the slice created in step 2. Where in some languages you might pass a starting index into an
indexmethod to find the second day, in Swift you perform the same operation on a slice of the original array.
Print the results using the indices found in steps 1 and 3 on the original
Here’s an implementation of those steps:
In particular, note that
j, the index of the second day with absences, was found in a slice of the original array and then used to access a value in the original
absences array itself.