Slice
A view into a subsequence of elements of another collection.
@frozen struct Slice<Base> where Base : Collection
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.
var absences = [0, 2, 0, 4, 0, 3, 1, 0]
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 steps:
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:
let secondHalf = absences.suffix(absences.count / 2)
if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) {
print("Highest second-half absences: \(absences[i])")
}
// Prints "Highest second-half absences: 3"
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 secondHalf
slice is unchanged.
absences[7] = 2
print(absences)
// Prints "[0, 2, 0, 4, 0, 3, 1, 2]"
print(secondHalf)
// Prints "[0, 3, 1, 0]"
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.
Citizens in Swift
Members
init(base: Base, bounds: Range<Base.Index>
) Creates a view into the given collection that allows access to elements within the specified range.
var base: Base
The underlying collection of the slice.
Citizens in Swift
where Base:Collection
Conformances
protocol Collection
A sequence whose elements can be traversed multiple times, nondestructively, and accessed by an indexed subscript.
protocol Sequence
A type that provides sequential, iterated access to its elements.
Members
var endIndex: Slice<Base>.Index
var indices: Slice<Base>.Indices
var startIndex: Slice<Base>.Index
subscript(Slice
<Base>.Index) -> Base.Element subscript(Range
<Slice<Base>.Index>) -> Slice<Base> func deinitialize<Element>(
) -> UnsafeMutableRawBufferPointer Deinitializes every instance in this buffer slice.
func deinitializeElement<Element>(at: UnsafeMutableBufferPointer<Element>.Index
) Deinitializes the memory underlying the element at
index
.func distance(from: Slice<Base>.Index, to: Slice<Base>.Index
) -> Int func formIndex(after: inout Slice<Base>.Index
) func index(Slice
<Base>.Index, offsetBy: Int) -> Slice<Base>.Index func index(Slice
<Base>.Index, offsetBy: Int, limitedBy: Slice<Base>.Index) -> Slice<Base>.Index? func index(after: Slice<Base>.Index
) -> Slice<Base>.Index func initialize<S>(from: S
) -> (unwritten: S.Iterator, index: Slice<Base>.Index) Initializes the buffer slice’s memory with the given elements.
func initialize<C>(fromContentsOf: C
) -> Slice<Base>.Index Initializes the buffer slice’s memory with with every element of the source.
func initialize<Element>(repeating: Element
) Initializes every element in this buffer slice’s memory to a copy of the given value.
func initializeElement<Element>(at: Int, to: Element
) Initializes the element at
index
to the given value.func moveElement<Element>(from: Slice<Base>.Index
) -> Element Retrieves and returns the element at
index
, leaving that element’s underlying memory uninitialized.func moveInitialize<Element>(fromContentsOf: Slice<UnsafeMutableBufferPointer<Element>>
) -> Slice<Base>.Index Moves every element of an initialized source buffer slice into the uninitialized memory referenced by this buffer slice, leaving the source memory uninitialized and this buffer slice’s memory initialized.
func moveInitialize<Element>(fromContentsOf: UnsafeMutableBufferPointer<Element>
) -> Slice<Base>.Index Moves every element of an initialized source buffer into the uninitialized memory referenced by this buffer slice, leaving the source memory uninitialized and this buffer slice’s memory initialized.
func moveUpdate<Element>(fromContentsOf: Slice<UnsafeMutableBufferPointer<Element>>
) -> Slice<Base>.Index Updates this buffer slice’s initialized memory initialized memory by moving every element from the source buffer slice, leaving the source memory uninitialized.
func moveUpdate<Element>(fromContentsOf: UnsafeMutableBufferPointer<Element>
) -> Slice<Base>.Index Updates this buffer slice’s initialized memory initialized memory by moving every element from the source buffer, leaving the source memory uninitialized.
func update<S>(from: S
) -> (unwritten: S.Iterator, index: Slice<Base>.Index) Updates the buffer slice’s initialized memory with the given elements.
func update<C>(fromContentsOf: C
) -> Slice<Base>.Index Updates the buffer slice’s initialized memory with every element of the source.
func update<Element>(repeating: Element
) Updates every element of this buffer slice’s initialized memory.
func withContiguousMutableStorageIfAvailable<R, Element>((inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? func withContiguousStorageIfAvailable<R>((UnsafeBufferPointer<Slice<Base>.Element>) throws -> R
) rethrows -> R? func withMemoryRebound<T, Result, Element>(to: T.Type, (UnsafeBufferPointer<T>) throws -> Result
) rethrows -> Result Executes the given closure while temporarily binding the memory referenced by this buffer slice to the given type.
func withMemoryRebound<T, Result, Element>(to: T.Type, (UnsafeMutableBufferPointer<T>) throws -> Result
) rethrows -> Result Executes the given closure while temporarily binding the memory referenced by this buffer slice to the given type.
typealias Element
typealias Index
typealias Indices
typealias Iterator
typealias SubSequence
Features
var first: Self.Element?
The first element of the collection.
var lazy: LazySequence<Self>
A sequence containing the same elements as this sequence, but on which some operations, such as
map
andfilter
, are implemented lazily.func allSatisfy((Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.
func compactMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] Returns an array containing the non-
nil
results of calling the given transformation with each element of this sequence.func contains(Self
.Element) -> Bool Returns a Boolean value indicating whether the sequence contains the given element.
func contains(where: (Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
func drop(while: (Self.Element) throws -> Bool
) rethrows -> Self.SubSequence Returns a subsequence by skipping elements while
predicate
returnstrue
and returning the remaining elements.func dropFirst(Int
) -> Self.SubSequence Returns a subsequence containing all but the given number of initial elements.
func dropLast(Int
) -> Self.SubSequence Returns a subsequence containing all but the specified number of final elements.
func elementsEqual<OtherSequence>(OtherSequence
) -> Bool Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.
func elementsEqual<OtherSequence>(OtherSequence, by: (Self.Element, OtherSequence.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements in the same order, using the given predicate as the equivalence test.
func enumerated(
) -> EnumeratedSequence<Self> Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.
func filter((Self.Element) throws -> Bool
) rethrows -> [Self.Element] Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
func first(where: (Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the first element of the sequence that satisfies the given predicate.
func firstIndex(of: Self.Element
) -> Self.Index? Returns the first index where the specified value appears in the collection.
func firstIndex(where: (Self.Element) throws -> Bool
) rethrows -> Self.Index? Returns the first index in which an element of the collection satisfies the given predicate.
func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.
func forEach((Self.Element) throws -> Void
) rethrows Calls the given closure on each element in the sequence in the same order as a
for
-in
loop.func formIndex(inout Self
.Index, offsetBy: Int) Offsets the given index by the specified distance.
func formIndex(inout Self
.Index, offsetBy: Int, limitedBy: Self.Index) -> Bool Offsets the given index by the specified distance, or so that it equals the given limiting index.
func joined(
) -> FlattenSequence<Self> Returns the elements of this sequence of sequences, concatenated.
func joined<Separator>(separator: Separator
) -> JoinedSequence<Self> Returns the concatenated elements of this sequence of sequences, inserting the given separator between each element.
func joined(separator: String
) -> String Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.
func lexicographicallyPrecedes<OtherSequence>(OtherSequence
) -> Bool Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (
<
) to compare elements.func lexicographicallyPrecedes<OtherSequence>(OtherSequence, by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.
func map<T>((Self.Element) throws -> T
) rethrows -> [T] Returns an array containing the results of mapping the given closure over the sequence’s elements.
func map<T>((Self.Element) throws -> T
) rethrows -> [T] Returns an array containing the results of mapping the given closure over the sequence’s elements.
func max(
) -> Self.Element? Returns the maximum element in the sequence.
func max(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
func min(
) -> Self.Element? Returns the minimum element in the sequence.
func min(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the minimum element in the sequence, using the given predicate as the comparison between elements.
func popFirst(
) -> Self.Element? Removes and returns the first element of the collection.
func prefix(Int
) -> Self.SubSequence Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.
func prefix(through: Self.Index
) -> Self.SubSequence Returns a subsequence from the start of the collection through the specified position.
func prefix(upTo: Self.Index
) -> Self.SubSequence Returns a subsequence from the start of the collection up to, but not including, the specified position.
func prefix(while: (Self.Element) throws -> Bool
) rethrows -> Self.SubSequence Returns a subsequence containing the initial elements until
predicate
returnsfalse
and skipping the remaining elements.func randomElement(
) -> Self.Element? Returns a random element of the collection.
func randomElement<T>(using: inout T
) -> Self.Element? Returns a random element of the collection, using the given generator as a source for randomness.
func reduce<Result>(Result, (Result, Self.Element) throws -> Result
) rethrows -> Result Returns the result of combining the elements of the sequence using the given closure.
func reduce<Result>(into: Result, (inout Result, Self.Element) throws -> ()
) rethrows -> Result Returns the result of combining the elements of the sequence using the given closure.
func removeFirst(
) -> Self.Element Removes and returns the first element of the collection.
func removeFirst(Int
) Removes the specified number of elements from the beginning of the collection.
func reversed(
) -> [Self.Element] Returns an array containing the elements of this sequence in reverse order.
func shuffled(
) -> [Self.Element] Returns the elements of the sequence, shuffled.
func shuffled<T>(using: inout T
) -> [Self.Element] Returns the elements of the sequence, shuffled using the given generator as a source for randomness.
func sorted(
) -> [Self.Element] Returns the elements of the sequence, sorted.
func sorted(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> [Self.Element] Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.
func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator: (Self.Element) throws -> Bool
) rethrows -> [Self.SubSequence] Returns the longest possible subsequences of the collection, in order, that don’t contain elements satisfying the given predicate.
func split(separator: Self.Element, maxSplits: Int, omittingEmptySubsequences: Bool
) -> [ArraySlice<Self.Element>] Returns the longest possible subsequences of the sequence, in order, around elements equal to the given element.
func split(separator: Self.Element, maxSplits: Int, omittingEmptySubsequences: Bool
) -> [Self.SubSequence] Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.
func starts<PossiblePrefix>(with: PossiblePrefix
) -> Bool Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.
func starts<PossiblePrefix>(with: PossiblePrefix, by: (Self.Element, PossiblePrefix.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether the initial elements of the sequence are equivalent to the elements in another sequence, using the given predicate as the equivalence test.
func suffix(Int
) -> Self.SubSequence Returns a subsequence, up to the given maximum length, containing the final elements of the collection.
func suffix(from: Self.Index
) -> Self.SubSequence Returns a subsequence from the specified position to the end of the collection.
func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] func index(of: Self.Element
) -> Self.Index? Returns the first index where the specified value appears in the collection.
Citizens in Swift
where Base:RandomAccessCollection
Conformances
protocol RandomAccessCollection
A collection that supports efficient random-access index traversal.
Citizens in Swift
where Base:BidirectionalCollection
Conformances
protocol BidirectionalCollection
A collection that supports backward as well as forward traversal.
Members
func formIndex(before: inout Slice<Base>.Index
) func index(before: Slice<Base>.Index
) -> Slice<Base>.Index
Features
var last: Self.Element?
The last element of the collection.
func difference<C>(from: C
) -> CollectionDifference<Self.Element> Returns the difference needed to produce this collection’s ordered elements from the given collection.
func difference<C>(from: C, by: (C.Element, Self.Element) -> Bool
) -> CollectionDifference<Self.Element> Returns the difference needed to produce this collection’s ordered elements from the given collection, using the given predicate as an equivalence test.
func joined(separator: String
) -> String Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.
func last(where: (Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the last element of the sequence that satisfies the given predicate.
func lastIndex(of: Self.Element
) -> Self.Index? Returns the last index where the specified value appears in the collection.
func lastIndex(where: (Self.Element) throws -> Bool
) rethrows -> Self.Index? Returns the index of the last element in the collection that matches the given predicate.
func popLast(
) -> Self.Element? Removes and returns the last element of the collection.
func removeLast(
) -> Self.Element Removes and returns the last element of the collection.
func removeLast(Int
) Removes the given number of elements from the end of the collection.
Citizens in Swift
where Base:Collection, Base:LazySequenceProtocol
Conformances
protocol LazySequenceProtocol
A sequence on which normally-eager sequence operations are implemented lazily.
Features
func compactMap<ElementOfResult>((Self.Elements.Element) -> ElementOfResult?
) -> LazyMapSequence<LazyFilterSequence<LazyMapSequence<Self.Elements, ElementOfResult?>>, ElementOfResult> Returns the non-
nil
results of mapping the given transformation over this sequence.func flatMap<SegmentOfResult>((Self.Elements.Element) -> SegmentOfResult
) -> LazySequence<FlattenSequence<LazyMapSequence<Self.Elements, SegmentOfResult>>> Returns the concatenated results of mapping the given transformation over this sequence.
func joined(
) -> LazySequence<FlattenSequence<Self.Elements>> Returns a lazy sequence that concatenates the elements of this sequence of sequences.
func map<U>((Self.Element) -> U
) -> LazyMapSequence<Self.Elements, U> Returns a
LazyMapSequence
over thisSequence
. The elements of the result are computed lazily, each time they are read, by callingtransform
function on a base element.func flatMap<ElementOfResult>((Self.Elements.Element) -> ElementOfResult?
) -> LazyMapSequence<LazyFilterSequence<LazyMapSequence<Self.Elements, ElementOfResult?>>, ElementOfResult> Returns the non-
nil
results of mapping the given transformation over this sequence.
Citizens in Swift
where Base:MutableCollection
Conformances
protocol MutableCollection
A collection that supports subscript assignment.
Members
subscript(Slice
<Base>.Index) -> Base.Element subscript(Range
<Slice<Base>.Index>) -> Slice<Base> func withContiguousMutableStorageIfAvailable<R>((inout UnsafeMutableBufferPointer<Slice<Base>.Element>) throws -> R
) rethrows -> R?
Features
func reverse(
) Reverses the elements of the collection in place.
func shuffle(
) Shuffles the collection in place.
func shuffle<T>(using: inout T
) Shuffles the collection in place, using the given generator as a source for randomness.
func sort(
) Sorts the collection in place.
func sort(by: (Self.Element, Self.Element) throws -> Bool
) rethrows Sorts the collection in place, using the given predicate as the comparison between elements.
Citizens in Swift
where Base:RangeReplaceableCollection
Conformances
protocol RangeReplaceableCollection
A collection that supports replacement of an arbitrary subrange of elements with the elements of another collection.
Members
init(
) init<S>(S
) init(repeating: Base.Element, count: Int
) func insert(Base
.Element, at: Slice<Base>.Index) func insert<S>(contentsOf: S, at: Slice<Base>.Index
) func remove(at: Slice<Base>.Index
) -> Base.Element func removeSubrange(Range
<Slice<Base>.Index>) func replaceSubrange<C>(Range
<Slice<Base>.Index>, with: C)
Features
static func + <Other>(Other, Self
) -> Self Creates a new collection by concatenating the elements of a sequence and a collection.
static func + <Other>(Self, Other
) -> Self Creates a new collection by concatenating the elements of a collection and a sequence.
static func + <Other>(Self, Other
) -> Self Creates a new collection by concatenating the elements of two collections.
static func += <Other>(inout Self, Other
) Appends the elements of a sequence to a range-replaceable collection.
func applying(CollectionDifference
<Self.Element>) -> Self? Applies the given difference to this collection.
func popLast(
) -> Self.Element? Removes and returns the last element of the collection.
func popLast(
) -> Self.Element? Removes and returns the last element of the collection.
func removeLast(
) -> Self.Element Removes and returns the last element of the collection.
func removeLast(
) -> Self.Element Removes and returns the last element of the collection.
func removeLast(Int
) Removes the specified number of elements from the end of the collection.
func removeLast(Int
) Removes the specified number of elements from the end of the collection.
Citizens in Swift
where Base:Collection, Base:Sendable, Base.Index:Sendable
Conformances
protocol Sendable
A type whose values can safely be passed across concurrency domains by copying.
Citizens in Swift
where Base:BidirectionalCollection, Base:RangeReplaceableCollection
Members
Citizens in Swift
where Base == UnsafeRawBufferPointer
Members
func assumingMemoryBound<T>(to: T.Type
) -> UnsafeBufferPointer<T> Returns a typed buffer to the memory referenced by this buffer slice, assuming that the memory is already bound to the specified type.
func bindMemory<T>(to: T.Type
) -> UnsafeBufferPointer<T> Binds this buffer slice’s memory to the specified type and returns a typed buffer of the bound memory.
func load<T>(fromByteOffset: Int, as: T.Type
) -> T Returns a new instance of the given type, read from the specified offset into the buffer pointer slice’s raw memory.
func loadUnaligned<T>(fromByteOffset: Int, as: T.Type
) -> T Returns a new instance of the given type, read from the specified offset into the buffer pointer slice’s raw memory.
func withMemoryRebound<T, Result>(to: T.Type, (UnsafeBufferPointer<T>) throws -> Result
) rethrows -> Result Executes the given closure while temporarily binding the buffer slice to instances of type
T
.
Citizens in Swift
where Base == UnsafeMutableRawBufferPointer
Members
func assumingMemoryBound<T>(to: T.Type
) -> UnsafeMutableBufferPointer<T> Returns a typed buffer to the memory referenced by this buffer slice, assuming that the memory is already bound to the specified type.
func bindMemory<T>(to: T.Type
) -> UnsafeMutableBufferPointer<T> Binds this buffer slice’s memory to the specified type and returns a typed buffer of the bound memory.
func copyBytes<C>(from: C
) Copies from a collection of
UInt8
into this buffer slice’s memory.func initializeMemory<S>(as: S.Element.Type, from: S
) -> (unwritten: S.Iterator, initialized: UnsafeMutableBufferPointer<S.Element>) Initializes the buffer’s memory with the given elements, binding the initialized memory to the elements’ type.
func initializeMemory<C>(as: C.Element.Type, fromContentsOf: C
) -> UnsafeMutableBufferPointer<C.Element> Initializes the buffer slice’s memory with every element of the source, binding the initialized memory to the elements’ type.
func initializeMemory<T>(as: T.Type, repeating: T
) -> UnsafeMutableBufferPointer<T> Initializes the memory referenced by this buffer slice with the given value, binds the memory to the value’s type, and returns a typed buffer of the initialized memory.
func load<T>(fromByteOffset: Int, as: T.Type
) -> T Returns a new instance of the given type, read from the specified offset into the buffer pointer slice’s raw memory.
func loadUnaligned<T>(fromByteOffset: Int, as: T.Type
) -> T Returns a new instance of the given type, read from the specified offset into the buffer pointer slice’s raw memory.
func moveInitializeMemory<T>(as: T.Type, fromContentsOf: Slice<UnsafeMutableBufferPointer<T>>
) -> UnsafeMutableBufferPointer<T> Moves every element from an initialized source buffer slice into the uninitialized memory referenced by this buffer slice, leaving the source memory uninitialized and this slice’s memory initialized.
func moveInitializeMemory<T>(as: T.Type, fromContentsOf: UnsafeMutableBufferPointer<T>
) -> UnsafeMutableBufferPointer<T> Moves every element of an initialized source buffer into the uninitialized memory referenced by this buffer slice, leaving the source memory uninitialized and this slice’s memory initialized.
func storeBytes<T>(of: T, toByteOffset: Int, as: T.Type
) Stores a value’s bytes into the buffer pointer slice’s raw memory at the specified byte offset.
func withMemoryRebound<T, Result>(to: T.Type, (UnsafeMutableBufferPointer<T>) throws -> Result
) rethrows -> Result Executes the given closure while temporarily binding the buffer slice to instances of type
T
.
Available in Foundation
where Base:DataProtocol
Conformances
Members
Features
Available in Foundation
where Base:ContiguousBytes, Base:Collection
Conformances
protocol ContiguousBytes
Indicates that the conforming type is a contiguous collection of raw bytes whose underlying storage is directly accessible by withUnsafeBytes.