Slice

struct Slice

A view into a subsequence of elements of another collection.

Inheritance Collection
Associated Types
public typealias Index = Base.Index

Valid indices consist of the position of every element and a "past the end" position that's not valid for use as a subscript argument.

public typealias Indices = Base.Indices
public typealias Element = Base.Element
public typealias SubSequence = Slice<Base>

This associated type appears as a requirement in the Sequence protocol, but it is restated here with stricter constraints. In a collection, the subsequence should also conform to Collection.

public typealias Iterator = IndexingIterator<Slice<Base>>

By default, a collection conforms to the Sequence protocol by supplying IndexingIterator as its associated Iterator type.

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 setps:

  1. Create a slice of the absences array that holds the second half of the days.
  2. Use the max(by:) method to determine the index of the day with the most absences.
  3. 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.

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.

Initializers

init init(base:bounds:) Required

Creates a view into the given collection that allows access to elements within the specified range.

It is unusual to need to call this method directly. Instead, create a slice of a collection by using the collection's range-based subscript or by using methods that return a subsequence.

let singleDigits = 0...9
let subSequence = singleDigits.dropFirst(5)
print(Array(subSequence))
// Prints "[5, 6, 7, 8, 9]"

In this example, the expression singleDigits.dropFirst(5)) is equivalent to calling this initializer with singleDigits and a range covering the last five items of singleDigits.indices.

Declaration

@inlinable public init(base: Base, bounds: Range<Base.Index>)

Instance Variables

var base Required

The underlying collection of the slice.

You can use a slice's base property to access its base collection. The following example declares singleDigits, a range of single digit integers, and then drops the first element to create a slice of that range, singleNonZeroDigits. The base property of the slice is equal to singleDigits.

let singleDigits = 0..<10
let singleNonZeroDigits = singleDigits.dropFirst()
// singleNonZeroDigits is a Slice<Range<Int>>

print(singleNonZeroDigits.count)
// Prints "9"
prints(singleNonZeroDigits.base.count)
// Prints "10"
print(singleDigits == singleNonZeroDigits.base)
// Prints "true"

Declaration

var base: Base
var count Required

The number of elements in the collection.

To check whether a collection is empty, use its isEmpty property instead of comparing count to zero. Unless the collection guarantees random-access performance, calculating count can be an O(n) operation.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var count: Int
var endIndex Required

The collection's "past the end" position---that is, the position one greater than the last valid subscript argument.

When you need a range that includes the last element of a collection, use the half-open range operator (..<) with endIndex. The ..< operator creates a range that doesn't include the upper bound, so it's always safe to use with endIndex. For example:

let numbers = [10, 20, 30, 40, 50]
if let index = numbers.firstIndex(of: 30) {
    print(numbers[index ..< numbers.endIndex])
}
// Prints "[30, 40, 50]"

If the collection is empty, endIndex is equal to startIndex.

Declaration

var endIndex: Slice<Base>.Index
var first Required

The first element of the collection.

If the collection is empty, the value of this property is nil.

let numbers = [10, 20, 30, 40, 50]
if let firstNumber = numbers.first {
    print(firstNumber)
}
// Prints "10"

Declaration

var first: Self.Element?
var indices Required

The indices that are valid for subscripting the collection, in ascending order.

A collection's indices property can hold a strong reference to the collection itself, causing the collection to be nonuniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can result in an unexpected copy of the collection. To avoid the unexpected copy, use the index(after:) method starting with startIndex to produce indices instead.

var c = MyFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex {
    c[i] /= 5
    i = c.index(after: i)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])

Declaration

var indices: Slice<Base>.Indices
var isEmpty Required

A Boolean value indicating whether the collection is empty.

When you need to check whether your collection is empty, use the isEmpty property instead of checking that the count property is equal to zero. For collections that don't conform to RandomAccessCollection, accessing the count property iterates through the elements of the collection.

let horseName = "Silver"
if horseName.isEmpty {
    print("I've been through the desert on a horse with no name.")
} else {
    print("Hi ho, \(horseName)!")
}
// Prints "Hi ho, Silver!")

Complexity: O(1)

Declaration

var isEmpty: Bool
var startIndex Required

The position of the first element in a nonempty collection.

If the collection is empty, startIndex is equal to endIndex.

Declaration

var startIndex: Slice<Base>.Index
var underestimatedCount Required

A value less than or equal to the number of elements in the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var underestimatedCount: Int

Subscripts

subscript subscript(bounds:) Required

Accesses a contiguous subrange of the collection's elements.

For example, using a PartialRangeFrom range expression with an array accesses the subrange from the start of the range expression until the end of the array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2..<5]
print(streetsSlice)
// ["Channing", "Douglas", "Evarts"]

The accessed slice uses the same indices for the same elements as the original collection. This example searches streetsSlice for one of the strings in the slice, and then uses that index in the original array.

let index = streetsSlice.firstIndex(of: "Evarts")!    // 4
print(streets[index])
// "Evarts"

Always use the slice's startIndex property instead of assuming that its indices start at a particular value. Attempting to access an element by using an index outside the bounds of the slice may result in a runtime error, even if that index is valid for the original collection.

print(streetsSlice.startIndex)
// 2
print(streetsSlice[2])
// "Channing"

print(streetsSlice[0])
// error: Index out of bounds
  • Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

@inlinable public subscript(bounds: Range<Slice<Base>.Index>) -> Slice<Base>
subscript subscript(index:) Required

Accesses the element at the specified position.

The following example accesses an element of an array through its subscript to print its value:

var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
print(streets[1])
// Prints "Bryant"

You can subscript a collection with any valid index other than the collection's end index. The end index refers to the position one past the last element of a collection, so it doesn't correspond with an element.

  • Parameter position: The position of the element to access. position must be a valid index of the collection that is not equal to the endIndex property.

Complexity: O(1)

Declaration

@inlinable public subscript(index: Slice<Base>.Index) -> Base.Element
subscript subscript(r:) Required

Accesses the contiguous subrange of the collection's elements specified by a range expression.

The range expression is converted to a concrete subrange relative to this collection. For example, using a PartialRangeFrom range expression with an array accesses the subrange from the start of the range expression until the end of the array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2...]
print(streetsSlice)
// ["Channing", "Douglas", "Evarts"]

The accessed slice uses the same indices for the same elements as the original collection uses. This example searches streetsSlice for one of the strings in the slice, and then uses that index in the original array.

let index = streetsSlice.firstIndex(of: "Evarts")    // 4
print(streets[index!])
// "Evarts"

Always use the slice's startIndex property instead of assuming that its indices start at a particular value. Attempting to access an element by using an index outside the bounds of the slice's indices may result in a runtime error, even if that index is valid for the original collection.

print(streetsSlice.startIndex)
// 2
print(streetsSlice[2])
// "Channing"

print(streetsSlice[0])
// error: Index out of bounds
  • Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

@inlinable public subscript<R>(r: R) where R: RangeExpression, Self.Index == R.Bound -> Self.SubSequence
subscript subscript(x:) Required

Declaration

@inlinable public subscript(x: (UnboundedRange_) -> ()) -> Self.SubSequence

Instance Methods

func distance(from start: Self.Index, to end: Self.Index) -> Int Required

Returns the distance between two indices.

Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the resulting distance.

Declaration

@inlinable public func distance(from start: Self.Index, to end: Self.Index) -> Int
func distance(from start: Slice<Base>.Index, to end: Slice<Base>.Index) -> Int Required

Returns the distance between two indices.

Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the resulting distance.

Declaration

@inlinable public func distance(from start: Slice<Base>.Index, to end: Slice<Base>.Index) -> Int
func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence Required

Returns a subsequence by skipping elements while predicate returns true and returning the remaining elements.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be skipped or false if it should be included. Once the predicate returns false it will not be called again.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
func dropFirst(_ k: Int = 1) -> Self.SubSequence Required

Returns a subsequence containing all but the given number of initial elements.

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst(2))
// Prints "[3, 4, 5]"
print(numbers.dropFirst(10))
// Prints "[]"
  • Parameter k: The number of elements to drop from the beginning of the collection. k must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to drop from the beginning of the collection.

Declaration

@inlinable public func dropFirst(_ k: Int = 1) -> Self.SubSequence
func dropLast(_ k: Int = 1) -> Self.SubSequence Required

Returns a subsequence containing all but the specified number of final elements.

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"
  • Parameter k: The number of elements to drop off the end of the collection. k must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

@inlinable public func dropLast(_ k: Int = 1) -> Self.SubSequence
func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index? Required

Returns the first index in which an element of the collection satisfies the given predicate.

You can use the predicate to find an element of a type that doesn't conform to the Equatable protocol or to find an element that matches particular criteria. Here's an example that finds a student name that begins with the letter "A":

let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.firstIndex(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Abena starts with 'A'!"
  • Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?
func formIndex(_ i: inout Self.Index, offsetBy distance: Int) Required

Offsets the given index by the specified distance.

The value passed as distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func formIndex(_ i: inout Self.Index, offsetBy distance: Int)
func formIndex(_ i: inout Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool Required

Offsets the given index by the specified distance, or so that it equals the given limiting index.

The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func formIndex(_ i: inout Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool
func formIndex(after i: inout Self.Index) Required

Replaces the given index with its successor.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

@inlinable public func formIndex(after i: inout Self.Index)
func formIndex(after i: inout Slice<Base>.Index) Required

Replaces the given index with its successor.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

@inlinable public func formIndex(after i: inout Slice<Base>.Index)
func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index Required

Returns an index that is the specified distance from the given index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position.

let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 4)
print(s[i])
// Prints "t"

The value passed as distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index
func index(_ i: Slice<Base>.Index, offsetBy n: Int) -> Slice<Base>.Index Required

Returns an index that is the specified distance from the given index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position.

let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 4)
print(s[i])
// Prints "t"

The value passed as distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: Slice<Base>.Index, offsetBy n: Int) -> Slice<Base>.Index
func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index? Required

Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position. The operation doesn't require going beyond the limiting s.endIndex value, so it succeeds.

let s = "Swift"
if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
    print(s[i])
}
// Prints "t"

The next example attempts to retrieve an index six positions from s.startIndex but fails, because that distance is beyond the index passed as limit.

let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
print(j)
// Prints "nil"

The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index?
func index(_ i: Slice<Base>.Index, offsetBy n: Int, limitedBy limit: Slice<Base>.Index) -> Slice<Base>.Index? Required

Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position. The operation doesn't require going beyond the limiting s.endIndex value, so it succeeds.

let s = "Swift"
if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
    print(s[i])
}
// Prints "t"

The next example attempts to retrieve an index six positions from s.startIndex but fails, because that distance is beyond the index passed as limit.

let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
print(j)
// Prints "nil"

The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: Slice<Base>.Index, offsetBy n: Int, limitedBy limit: Slice<Base>.Index) -> Slice<Base>.Index?
func index(after i: Slice<Base>.Index) -> Slice<Base>.Index Required

Returns the position immediately after the given index.

The successor of an index must be well defined. For an index i into a collection c, calling c.index(after: i) returns the same index every time.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

@inlinable public func index(after i: Slice<Base>.Index) -> Slice<Base>.Index
func map(_ transform: (Self.Element) throws -> T) rethrows -> [T] Required

Returns an array containing the results of mapping the given closure over the sequence's elements.

In this example, map is used first to convert the names in the array to lowercase strings and then to count their characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]
  • Parameter transform: A mapping closure. transform accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type.

Declaration

@inlinable public func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
func prefix(_ maxLength: Int) -> Self.SubSequence Required

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to select from the beginning of the collection.

Declaration

@inlinable public func prefix(_ maxLength: Int) -> Self.SubSequence
func prefix(through position: Self.Index) -> Self.SubSequence Required

Returns a subsequence from the start of the collection through the specified position.

The resulting subsequence includes the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, and including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(through: i))
}
// Prints "[10, 20, 30, 40]"

Using the prefix(through:) method is equivalent to using a partial closed range as the collection's subscript. The subscript notation is preferred over prefix(through:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[...i])
}
// Prints "[10, 20, 30, 40]"
  • Parameter end: The index of the last element to include in the resulting subsequence. end must be a valid index of the collection that is not equal to the endIndex property.

Complexity: O(1)

Declaration

@inlinable public func prefix(through position: Self.Index) -> Self.SubSequence
func prefix(upTo end: Self.Index) -> Self.SubSequence Required

Returns a subsequence from the start of the collection up to, but not including, the specified position.

The resulting subsequence does not include the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, but not including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(upTo: i))
}
// Prints "[10, 20, 30]"

Passing the collection's starting index as the end parameter results in an empty subsequence.

print(numbers.prefix(upTo: numbers.startIndex))
// Prints "[]"

Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over prefix(upTo:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[..<i])
}
// Prints "[10, 20, 30]"
  • Parameter end: The "past the end" index of the resulting subsequence. end must be a valid index of the collection.

Complexity: O(1)

Declaration

@inlinable public func prefix(upTo end: Self.Index) -> Self.SubSequence
func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence Required

Returns a subsequence containing the initial elements until predicate returns false and skipping the remaining elements.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be included or false if it should be excluded. Once the predicate returns false it will not be called again.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
func randomElement() -> Self.Element? Required

Returns a random element of the collection.

Call randomElement() to select a random element from an array or another collection. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement()!
// randomName == "Amani"

This method is equivalent to calling randomElement(using:), passing in the system's default random generator.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

@inlinable public func randomElement() -> Self.Element?
func randomElement(using generator: inout T) -> Self.Element? Required

Returns a random element of the collection, using the given generator as a source for randomness.

Call randomElement(using:) to select a random element from an array or another collection when you are using a custom random number generator. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement(using: &myGenerator)!
// randomName == "Amani"
  • Parameter generator: The random number generator to use when choosing a random element.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Note: The algorithm used to select a random element may change in a future version of Swift. If you're passing a generator that results in the same sequence of elements each time you run your program, that sequence may change when your program is compiled using a different version of Swift.

Declaration

@inlinable public func randomElement<T>(using generator: inout T) -> Self.Element? where T: RandomNumberGenerator
func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence] Required

Returns the longest possible subsequences of the collection, in order, that don't contain elements satisfying the given predicate.

The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the sequence are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string using a closure that matches spaces. The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(line.split(maxSplits: 1, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes false for the omittingEmptySubsequences parameter, so the returned array contains empty strings where spaces were repeated.

print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence]
func suffix(_ maxLength: Int) -> Self.SubSequence Required

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

@inlinable public func suffix(_ maxLength: Int) -> Self.SubSequence
func suffix(from start: Self.Index) -> Self.SubSequence Required

Returns a subsequence from the specified position to the end of the collection.

The following example searches for the index of the number 40 in an array of integers, and then prints the suffix of the array starting at that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.suffix(from: i))
}
// Prints "[40, 50, 60]"

Passing the collection's endIndex as the start parameter results in an empty subsequence.

print(numbers.suffix(from: numbers.endIndex))
// Prints "[]"

Using the suffix(from:) method is equivalent to using a partial range from the index as the collection's subscript. The subscript notation is preferred over suffix(from:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[i...])
}
// Prints "[40, 50, 60]"
  • Parameter start: The index at which to start the resulting subsequence. start must be a valid index of the collection.

Complexity: O(1)

Declaration

@inlinable public func suffix(from start: Self.Index) -> Self.SubSequence
func withContiguousStorageIfAvailable(_ body: (UnsafeBufferPointer<Slice<Base>.Element>) throws -> R) rethrows -> R? Required

Call body(p), where p is a pointer to the collection's contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of contiguous storage, body is not called and nil is returned.

A Collection that provides its own implementation of this method must also guarantee that an equivalent buffer of its SubSequence can be generated by advancing the pointer by the distance to the slice's startIndex.

Declaration

@inlinable public func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<Slice<Base>.Element>) throws -> R) rethrows -> R?