## PartialRangeFrom

`struct PartialRangeFrom<Bound>`

A partial interval extending upward from a lower bound.

You create `PartialRangeFrom` instances by using the postfix range operator (postfix `...`).

``let atLeastFive = 5...``

You can use a partial range to quickly check if a value is contained in a particular range of values. For example:

``````atLeastFive.contains(4)
// false
atLeastFive.contains(5)
// true
atLeastFive.contains(6)
// true``````

You can use a partial range of a collection's indices to represent the range from the partial range's lower bound up to the end of the collection.

``````let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[3...])
// Prints "[40, 50, 60, 70]"``````

## Using a Partial Range as a Sequence

When a partial range uses integers as its lower and upper bounds, or any other type that conforms to the `Strideable` protocol with an integer stride, you can use that range in a `for`-`in` loop or with any sequence method that doesn't require that the sequence is finite. The elements of a partial range are the consecutive values from its lower bound continuing upward indefinitely.

``````func isTheMagicNumber(_ x: Int) -> Bool {
return x == 3
}

for x in 1... {
if isTheMagicNumber(x) {
print("\(x) is the magic number!")
break
} else {
print("\(x) wasn't it...")
}
}
// "1 wasn't it..."
// "2 wasn't it..."
// "3 is the magic number!"``````

Because a `PartialRangeFrom` sequence counts upward indefinitely, do not use one with methods that read the entire sequence before returning, such as `map(_:)`, `filter(_:)`, or `suffix(_:)`. It is safe to use operations that put an upper limit on the number of elements they access, such as `prefix(_:)` or `dropFirst(_:)`, and operations that you can guarantee will terminate, such as passing a closure you know will eventually return `true` to `first(where:)`.

In the following example, the `asciiTable` sequence is made by zipping together the characters in the `alphabet` string with a partial range starting at 65, the ASCII value of the capital letter A. Iterating over two zipped sequences continues only as long as the shorter of the two sequences, so the iteration stops at the end of `alphabet`.

``````let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let asciiTable = zip(65..., alphabet)
for (code, letter) in asciiTable {
print(code, letter)
}
// "65 A"
// "66 B"
// "67 C"
// ...
// "89 Y"
// "90 Z"``````

The behavior of incrementing indefinitely is determined by the type of `Bound`. For example, iterating over an instance of `PartialRangeFrom<Int>` traps when the sequence's next value would be above `Int.max`.

Inheritance `RangeExpression, Sequence` View Protocol Hierarchy → `Element = Bound` A type representing the sequence's elements. `PartialRangeFrom.Iterator` `import Swift`

### Initializers

init(_:)

#### Declaration

`init(_ lowerBound: PartialRangeFrom<Bound>.Bound)`

### Instance Variables

var lazy: LazySequence<PartialRangeFrom<Bound>>

A sequence containing the same elements as this sequence, but on which some operations, such as `map` and `filter`, are implemented lazily.

#### Declaration

`var lazy: LazySequence<PartialRangeFrom<Bound>> { get }`

#### Declared In

`Sequence`
var lowerBound: Bound

#### Declaration

`var lowerBound: Bound { get }`
var underestimatedCount: Int

A value less than or equal to the number of elements in the sequence, calculated nondestructively.

The default implementation returns 0. If you provide your own implementation, make sure to compute the value nondestructively.

Complexity: O(1), except if the sequence also conforms to `Collection`. In this case, see the documentation of `Collection.underestimatedCount`.

#### Declaration

`var underestimatedCount: Int { get }`

#### Declared In

`Sequence`

### Instance Methods

func allSatisfy(_:)

Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.

`predicate`: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition. Returns: `true` if the sequence contains only elements that satisfy `predicate`; otherwise, `false`.

#### Declaration

`func allSatisfy(_ predicate: (PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> Bool`

#### Declared In

`Sequence`
func compactMap(_:)

Returns an array containing the non-`nil` results of calling the given transformation with each element of this sequence.

Use this method to receive an array of nonoptional values when your transformation produces an optional value.

In this example, note the difference in the result of using `map` and `compactMap` with a transformation that returns an optional `Int` value.

``````let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]``````

`transform`: A closure that accepts an element of this sequence as its argument and returns an optional value. Returns: An array of the non-`nil` results of calling `transform` with each element of the sequence.

Complexity: O(m + n), where m is the length of this sequence and n is the length of the result.

#### Declaration

`func compactMap<ElementOfResult>(_ transform: (PartialRangeFrom<Bound>.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]`

#### Declared In

`Sequence`
func contains(_:)

Returns a Boolean value indicating whether the given element is contained within the range expression.

`element`: The element to check for containment. Returns: `true` if `element` is contained in the range expression; otherwise, `false`.

#### Declaration

`func contains(_ element: Bound) -> Bool`
func contains(where:)

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

You can use the predicate to check for an element of a type that doesn't conform to the `Equatable` protocol, such as the `HTTPResponse` enumeration in this example.

``````enum HTTPResponse {
case ok
case error(Int)
}

let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
let hadError = lastThreeResponses.contains { element in
if case .error = element {
return true
} else {
return false
}
}

Alternatively, a predicate can be satisfied by a range of `Equatable` elements or a general condition. This example shows how you can check an array for an expense greater than \$100.

``````let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
let hasBigPurchase = expenses.contains { \$0 > 100 }
// 'hasBigPurchase' == true``````

`predicate`: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match. Returns: `true` if the sequence contains an element that satisfies `predicate`; otherwise, `false`.

#### Declaration

`func contains(where predicate: (PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> Bool`

#### Declared In

`Sequence`
func dropFirst()

Returns a subsequence containing all but the first element of the sequence.

The following example drops the first element from an array of integers.

``````let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst())
// Prints "[2, 3, 4, 5]"``````

If the sequence has no elements, the result is an empty subsequence.

``````let empty: [Int] = []
print(empty.dropFirst())
// Prints "[]"``````

Returns: A subsequence starting after the first element of the sequence.

Complexity: O(1)

#### Declaration

`func dropFirst() -> PartialRangeFrom<Bound>.SubSequence`

#### Declared In

`Sequence`
func dropLast()

Returns a subsequence containing all but the last element of the sequence.

The sequence must be finite.

``````let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast())
// Prints "[1, 2, 3, 4]"``````

If the sequence has no elements, the result is an empty subsequence.

``````let empty: [Int] = []
print(empty.dropLast())
// Prints "[]"``````

Returns: A subsequence leaving off the last element of the sequence.

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

#### Declaration

`func dropLast() -> PartialRangeFrom<Bound>.SubSequence`

#### Declared In

`Sequence`
func elementsEqual(_:by:)

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.

At least one of the sequences must be finite.

The predicate must be a equivalence relation over the elements. That is, for any elements `a`, `b`, and `c`, the following conditions must hold:

• `areEquivalent(a, a)` is always `true`. (Reflexivity)
• `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
• If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then `areEquivalent(a, c)` is also `true`. (Transitivity)

Parameters: other: A sequence to compare to this sequence. areEquivalent: A predicate that returns `true` if its two arguments are equivalent; otherwise, `false`. Returns: `true` if this sequence and `other` contain equivalent items, using `areEquivalent` as the equivalence test; otherwise, `false.`

#### Declaration

`func elementsEqual<OtherSequence>(_ other: OtherSequence, by areEquivalent: (PartialRangeFrom<Bound>.Element, OtherSequence.Element) throws -> Bool) rethrows -> Bool where OtherSequence : Sequence`

#### Declared In

`Sequence`
func enumerated()

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

This example enumerates the characters of the string "Swift" and prints each character along with its place in the string.

``````for (n, c) in "Swift".enumerated() {
print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"``````

When you enumerate a collection, the integer part of each pair is a counter for the enumeration, but is not necessarily the index of the paired value. These counters can be used as indices only in instances of zero-based, integer-indexed collections, such as `Array` and `ContiguousArray`. For other collections the counters may be out of range or of the wrong type to use as an index. To iterate over the elements of a collection with its indices, use the `zip(_:_:)` function.

This example iterates over the indices and elements of a set, building a list consisting of indices of names with five or fewer letters.

``````let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
var shorterIndices: [SetIndex<String>] = []
for (i, name) in zip(names.indices, names) {
if name.count <= 5 {
shorterIndices.append(i)
}
}``````

Now that the `shorterIndices` array holds the indices of the shorter names in the `names` set, you can use those indices to access elements in the set.

``````for i in shorterIndices {
print(names[i])
}
// Prints "Sofia"
// Prints "Mateo"``````

Returns: A sequence of pairs enumerating the sequence.

#### Declaration

`func enumerated() -> EnumeratedSequence<PartialRangeFrom<Bound>>`

#### Declared In

`Sequence`
func filter(_:)

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

In this example, `filter(_:)` is used to include only names shorter than five characters.

``````let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { \$0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"``````

`isIncluded`: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array. Returns: An array of the elements that `isIncluded` allowed.

#### Declaration

`func filter(_ isIncluded: (PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> [PartialRangeFrom<Bound>.Element]`

#### Declared In

`Sequence`
func first(where:)

Returns the first element of the sequence that satisfies the given predicate.

The following example uses the `first(where:)` method to find the first negative number in an array of integers:

``````let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers.first(where: { \$0 < 0 }) {
print("The first negative number is \(firstNegative).")
}
// Prints "The first negative number is -2."``````

`predicate`: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. Returns: The first element of the sequence that satisfies `predicate`, or `nil` if there is no element that satisfies `predicate`.

#### Declaration

`func first(where predicate: (PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> PartialRangeFrom<Bound>.Element?`

#### Declared In

`Sequence`
func flatMap<ElementOfResult>(_: (PartialRangeFrom<Bound>.Element) throws -> ElementOfResult?)

Returns an array containing the non-`nil` results of calling the given transformation with each element of this sequence.

Use this method to receive an array of nonoptional values when your transformation produces an optional value.

In this example, note the difference in the result of using `map` and `flatMap` with a transformation that returns an optional `Int` value.

``````let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let flatMapped: [Int] = possibleNumbers.flatMap { str in Int(str) }
// [1, 2, 5]``````

`transform`: A closure that accepts an element of this sequence as its argument and returns an optional value. Returns: An array of the non-`nil` results of calling `transform` with each element of the sequence.

Complexity: O(m + n), where m is the length of this sequence and n is the length of the result.

#### Declaration

`func flatMap<ElementOfResult>(_ transform: (PartialRangeFrom<Bound>.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]`

#### Declared In

`Sequence`
func flatMap<SegmentOfResult>(_: (PartialRangeFrom<Bound>.Element) throws -> SegmentOfResult)

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

Use this method to receive a single-level collection when your transformation produces a sequence or collection for each element.

In this example, note the difference in the result of using `map` and `flatMap` with a transformation that returns an array.

``````let numbers = [1, 2, 3, 4]

let mapped = numbers.map { Array(repeating: \$0, count: \$0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

let flatMapped = numbers.flatMap { Array(repeating: \$0, count: \$0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]``````

In fact, `s.flatMap(transform)` is equivalent to `Array(s.map(transform).joined())`.

`transform`: A closure that accepts an element of this sequence as its argument and returns a sequence or collection. Returns: The resulting flattened array.

Complexity: O(m + n), where m is the length of this sequence and n is the length of the result.

#### Declaration

`func flatMap<SegmentOfResult>(_ transform: (PartialRangeFrom<Bound>.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence`

#### Declared In

`Sequence`
func forEach(_:)

Calls the given closure on each element in the sequence in the same order as a `for`-`in` loop.

The two loops in the following example produce the same output:

``````let numberWords = ["one", "two", "three"]
for word in numberWords {
print(word)
}
// Prints "one"
// Prints "two"
// Prints "three"

numberWords.forEach { word in
print(word)
}
// Same as above``````

Using the `forEach` method is distinct from a `for`-`in` loop in two important ways:

1. You cannot use a `break` or `continue` statement to exit the current call of the `body` closure or skip subsequent calls.
2. Using the `return` statement in the `body` closure will exit only from the current call to `body`, not from any outer scope, and won't skip subsequent calls.

`body`: A closure that takes an element of the sequence as a parameter.

#### Declaration

`func forEach(_ body: (PartialRangeFrom<Bound>.Element) throws -> Void) rethrows`

#### Declared In

`Sequence`
func lexicographicallyPrecedes(_:by:)

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.

The predicate must be a strict weak ordering over the elements. That is, for any elements `a`, `b`, and `c`, the following conditions must hold:

• `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
• If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are both `true`, then `areInIncreasingOrder(a, c)` is also `true`. (Transitive comparability)
• Two elements are incomparable if neither is ordered before the other according to the predicate. If `a` and `b` are incomparable, and `b` and `c` are incomparable, then `a` and `c` are also incomparable. (Transitive incomparability)

Parameters: other: A sequence to compare to this sequence. areInIncreasingOrder: A predicate that returns `true` if its first argument should be ordered before its second argument; otherwise, `false`. Returns: `true` if this sequence precedes `other` in a dictionary ordering as ordered by `areInIncreasingOrder`; otherwise, `false`.

Note: This method implements the mathematical notion of lexicographical ordering, which has no connection to Unicode. If you are sorting strings to present to the end user, use `String` APIs that perform localized comparison instead.

#### Declaration

`func lexicographicallyPrecedes<OtherSequence>(_ other: OtherSequence, by areInIncreasingOrder: (PartialRangeFrom<Bound>.Element, PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> Bool where OtherSequence : Sequence, PartialRangeFrom<Bound>.Element == OtherSequence.Element`

#### Declared In

`Sequence`
func makeIterator()

Returns an iterator for this sequence.

#### Declaration

`func makeIterator() -> PartialRangeFrom<Bound>.Iterator`
func map(_:)

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]``````

`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. Returns: An array containing the transformed elements of this sequence.

#### Declaration

`func map<T>(_ transform: (PartialRangeFrom<Bound>.Element) throws -> T) rethrows -> [T]`

#### Declared In

`Sequence`
@warn_unqualified_access func max(by:)

Returns the maximum element in the sequence, using the given predicate as the comparison between elements.

The predicate must be a strict weak ordering over the elements. That is, for any elements `a`, `b`, and `c`, the following conditions must hold:

• `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
• If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are both `true`, then `areInIncreasingOrder(a, c)` is also `true`. (Transitive comparability)
• Two elements are incomparable if neither is ordered before the other according to the predicate. If `a` and `b` are incomparable, and `b` and `c` are incomparable, then `a` and `c` are also incomparable. (Transitive incomparability)

This example shows how to use the `max(by:)` method on a dictionary to find the key-value pair with the highest value.

``````let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue)
// Prints "Optional(("Heliotrope", 296))"``````

`areInIncreasingOrder`: A predicate that returns `true` if its first argument should be ordered before its second argument; otherwise, `false`. Returns: The sequence's maximum element if the sequence is not empty; otherwise, `nil`.

#### Declaration

```@warn_unqualified_access func max(by areInIncreasingOrder: (PartialRangeFrom<Bound>.Element, PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> PartialRangeFrom<Bound>.Element?```

#### Declared In

`Sequence`
func min(by:)

Returns the minimum element in the sequence, using the given predicate as the comparison between elements.

The predicate must be a strict weak ordering over the elements. That is, for any elements `a`, `b`, and `c`, the following conditions must hold:

• `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
• If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are both `true`, then `areInIncreasingOrder(a, c)` is also `true`. (Transitive comparability)
• Two elements are incomparable if neither is ordered before the other according to the predicate. If `a` and `b` are incomparable, and `b` and `c` are incomparable, then `a` and `c` are also incomparable. (Transitive incomparability)

This example shows how to use the `min(by:)` method on a dictionary to find the key-value pair with the lowest value.

``````let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let leastHue = hues.min { a, b in a.value < b.value }
print(leastHue)
// Prints "Optional(("Coral", 16))"``````

`areInIncreasingOrder`: A predicate that returns `true` if its first argument should be ordered before its second argument; otherwise, `false`. Returns: The sequence's minimum element, according to `areInIncreasingOrder`. If the sequence has no elements, returns `nil`.

#### Declaration

`func min(by areInIncreasingOrder: (PartialRangeFrom<Bound>.Element, PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> PartialRangeFrom<Bound>.Element?`

#### Declared In

`Sequence`
func reduce(_:_:)

Returns the result of combining the elements of the sequence using the given closure.

Use the `reduce(_:_:)` method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product.

The `nextPartialResult` closure is called sequentially with an accumulating value initialized to `initialResult` and each element of the sequence. This example shows how to find the sum of an array of numbers.

``````let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10``````

When `numbers.reduce(_:_:)` is called, the following steps occur:

1. The `nextPartialResult` closure is called with `initialResult`---`0` in this case---and the first element of `numbers`, returning the sum: `1`.
2. The closure is called again repeatedly with the previous call's return value and each element of the sequence.
3. When the sequence is exhausted, the last value returned from the closure is returned to the caller.

If the sequence has no elements, `nextPartialResult` is never executed and `initialResult` is the result of the call to `reduce(_:_:)`.

Parameters: initialResult: The value to use as the initial accumulating value. `initialResult` is passed to `nextPartialResult` the first time the closure is executed. nextPartialResult: A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the `nextPartialResult` closure or returned to the caller. Returns: The final accumulated value. If the sequence has no elements, the result is `initialResult`.

#### Declaration

`func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, PartialRangeFrom<Bound>.Element) throws -> Result) rethrows -> Result`

#### Declared In

`Sequence`
func reduce(into:_:)

Returns the result of combining the elements of the sequence using the given closure.

Use the `reduce(into:_:)` method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of integers to filter adjacent equal entries or count frequencies.

This method is preferred over `reduce(_:_:)` for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.

The `updateAccumulatingResult` closure is called sequentially with a mutable accumulating value initialized to `initialResult` and each element of the sequence. This example shows how to build a dictionary of letter frequencies of a string.

``````let letters = "abracadabra"
let letterCount = letters.reduce(into: [:]) { counts, letter in
counts[letter, default: 0] += 1
}
// letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]``````

When `letters.reduce(into:_:)` is called, the following steps occur:

1. The `updateAccumulatingResult` closure is called with the initial accumulating value---`[:]` in this case---and the first character of `letters`, modifying the accumulating value by setting `1` for the key `"a"`.
2. The closure is called again repeatedly with the updated accumulating value and each element of the sequence.
3. When the sequence is exhausted, the accumulating value is returned to the caller.

If the sequence has no elements, `updateAccumulatingResult` is never executed and `initialResult` is the result of the call to `reduce(into:_:)`.

Parameters: initialResult: The value to use as the initial accumulating value. updateAccumulatingResult: A closure that updates the accumulating value with an element of the sequence. Returns: The final accumulated value. If the sequence has no elements, the result is `initialResult`.

#### Declaration

`func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, PartialRangeFrom<Bound>.Element) throws -> ()) rethrows -> Result`

#### Declared In

`Sequence`
func relative(to:)

Returns the range of indices described by this range expression within the given collection.

You can use the `relative(to:)` method to convert a range expression, which could be missing one or both of its endpoints, into a concrete range that is bounded on both sides. The following example uses this method to convert a partial range up to `4` into a half-open range, using an array instance to add the range's lower bound.

``````let numbers = [10, 20, 30, 40, 50, 60, 70]
let upToFour = ..<4

let r1 = upToFour.relative(to: numbers)
// r1 == 0..<4``````

The `r1` range is bounded on the lower end by `0` because that is the starting index of the `numbers` array. When the collection passed to `relative(to:)` starts with a different index, that index is used as the lower bound instead. The next example creates a slice of `numbers` starting at index `2`, and then uses the slice with `relative(to:)` to convert `upToFour` to a concrete range.

``````let numbersSuffix = numbers[2...]
// numbersSuffix == [30, 40, 50, 60, 70]

// r2 == 2..<4``````

Use this method only if you need the concrete range it produces. To access a slice of a collection using a range expression, use the collection's generic subscript that uses a range expression as its parameter.

``````let numbersPrefix = numbers[upToFour]
// numbersPrefix == [10, 20, 30, 40]``````

`collection`: The collection to evaluate this range expression in relation to. Returns: A range suitable for slicing `collection`. The returned range is not guaranteed to be inside the bounds of `collection`. Callers should apply the same preconditions to the return value as they would to a range provided directly by the user.

#### Declaration

`func relative<C>(to collection: C) -> Range<Bound> where Bound == C.Index, C : Collection`
func reversed()

Returns an array containing the elements of this sequence in reverse order.

The sequence must be finite.

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

Returns: An array containing the elements of this sequence in reverse order.

#### Declaration

`func reversed() -> [PartialRangeFrom<Bound>.Element]`

#### Declared In

`Sequence`
func shuffled()

Returns the elements of the sequence, shuffled.

For example, you can shuffle the numbers between `0` and `9` by calling the `shuffled()` method on that range:

``````let numbers = 0...9
let shuffledNumbers = numbers.shuffled()
// shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0]``````

This method uses the default random generator, `Random.default`. The call to `numbers.shuffled()` above is equivalent to calling `numbers.shuffled(using: &Random.default)`.

Returns: A shuffled array of this sequence's elements.

Complexity: O(n)

#### Declaration

`func shuffled() -> [PartialRangeFrom<Bound>.Element]`

#### Declared In

`Sequence`
func shuffled(using:)

Returns the elements of the sequence, shuffled using the given generator as a source for randomness.

You use this method to randomize the elements of a sequence when you are using a custom random number generator. For example, you can shuffle the numbers between `0` and `9` by calling the `shuffled(using:)` method on that range:

``````let numbers = 0...9
let shuffledNumbers = numbers.shuffled(using: &myGenerator)
// shuffledNumbers == [8, 9, 4, 3, 2, 6, 7, 0, 5, 1]``````

`generator`: The random number generator to use when shuffling the sequence. Returns: An array of this sequence's elements in a shuffled order.

Complexity: O(n)

#### Declaration

`func shuffled<T>(using generator: inout T) -> [PartialRangeFrom<Bound>.Element] where T : RandomNumberGenerator`

#### Declared In

`Sequence`
func sorted(by:)

Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.

When you want to sort a sequence of elements that don't conform to the `Comparable` protocol, pass a predicate to this method that returns `true` when the first element passed should be ordered before the second. The elements of the resulting array are ordered according to the given predicate.

The predicate must be a strict weak ordering over the elements. That is, for any elements `a`, `b`, and `c`, the following conditions must hold:

• `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
• If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are both `true`, then `areInIncreasingOrder(a, c)` is also `true`. (Transitive comparability)
• Two elements are incomparable if neither is ordered before the other according to the predicate. If `a` and `b` are incomparable, and `b` and `c` are incomparable, then `a` and `c` are also incomparable. (Transitive incomparability)

The sorting algorithm is not stable. A nonstable sort may change the relative order of elements for which `areInIncreasingOrder` does not establish an order.

In the following example, the predicate provides an ordering for an array of a custom `HTTPResponse` type. The predicate orders errors before successes and sorts the error responses by their error code.

``````enum HTTPResponse {
case ok
case error(Int)
}

let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
let sortedResponses = responses.sorted {
switch (\$0, \$1) {
// Order errors by code
case let (.error(aCode), .error(bCode)):
return aCode < bCode

// All successes are equivalent, so none is before any other
case (.ok, .ok): return false

// Order errors before successes
case (.error, .ok): return true
case (.ok, .error): return false
}
}
print(sortedResponses)
// Prints "[.error(403), .error(404), .error(500), .ok, .ok]"``````

You also use this method to sort elements that conform to the `Comparable` protocol in descending order. To sort your sequence in descending order, pass the greater-than operator (`>`) as the `areInIncreasingOrder` parameter.

``````let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let descendingStudents = students.sorted(by: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"``````

Calling the related `sorted()` method is equivalent to calling this method and passing the less-than operator (`<`) as the predicate.

``````print(students.sorted())
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
print(students.sorted(by: <))
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"``````

`areInIncreasingOrder`: A predicate that returns `true` if its first argument should be ordered before its second argument; otherwise, `false`. Returns: A sorted array of the sequence's elements.

#### Declaration

`func sorted(by areInIncreasingOrder: (PartialRangeFrom<Bound>.Element, PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> [PartialRangeFrom<Bound>.Element]`

#### Declared In

`Sequence`
func starts(with:by:)

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.

The predicate must be a equivalence relation over the elements. That is, for any elements `a`, `b`, and `c`, the following conditions must hold:

• `areEquivalent(a, a)` is always `true`. (Reflexivity)
• `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
• If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then `areEquivalent(a, c)` is also `true`. (Transitivity)

Parameters: possiblePrefix: A sequence to compare to this sequence. areEquivalent: A predicate that returns `true` if its two arguments are equivalent; otherwise, `false`. Returns: `true` if the initial elements of the sequence are equivalent to the elements of `possiblePrefix`; otherwise, `false`. If `possiblePrefix` has no elements, the return value is `true`.

#### Declaration

`func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix, by areEquivalent: (PartialRangeFrom<Bound>.Element, PossiblePrefix.Element) throws -> Bool) rethrows -> Bool where PossiblePrefix : Sequence`

#### Declared In

`Sequence`

### Conditionally Inherited Items

The initializers, methods, and properties listed below may be available on this type under certain conditions (such as methods that are available on `Array` when its elements are `Equatable`) or may not ever be available if that determination is beyond SwiftDoc.org's capabilities. Please open an issue on GitHub if you see something out of place!

#### Where Element : Comparable

func lexicographicallyPrecedes(_:)

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (`<`) to compare elements.

This example uses the `lexicographicallyPrecedes` method to test which array of integers comes first in a lexicographical ordering.

``````let a = [1, 2, 2, 2]
let b = [1, 2, 3, 4]

print(a.lexicographicallyPrecedes(b))
// Prints "true"
print(b.lexicographicallyPrecedes(b))
// Prints "false"``````

`other`: A sequence to compare to this sequence. Returns: `true` if this sequence precedes `other` in a dictionary ordering; otherwise, `false`.

Note: This method implements the mathematical notion of lexicographical ordering, which has no connection to Unicode. If you are sorting strings to present to the end user, use `String` APIs that perform localized comparison.

#### Declaration

`func lexicographicallyPrecedes<OtherSequence>(_ other: OtherSequence) -> Bool where OtherSequence : Sequence, PartialRangeFrom<Bound>.Element == OtherSequence.Element`

#### Declared In

`Sequence`
@warn_unqualified_access func max()

Returns the maximum element in the sequence.

This example finds the largest value in an array of height measurements.

``````let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let greatestHeight = heights.max()
print(greatestHeight)
// Prints "Optional(67.5)"``````

Returns: The sequence's maximum element. If the sequence has no elements, returns `nil`.

#### Declaration

```@warn_unqualified_access func max() -> PartialRangeFrom<Bound>.Element?```

#### Declared In

`Sequence`
@warn_unqualified_access func min()

Returns the minimum element in the sequence.

This example finds the smallest value in an array of height measurements.

``````let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let lowestHeight = heights.min()
print(lowestHeight)
// Prints "Optional(58.5)"``````

Returns: The sequence's minimum element. If the sequence has no elements, returns `nil`.

#### Declaration

```@warn_unqualified_access func min() -> PartialRangeFrom<Bound>.Element?```

#### Declared In

`Sequence`
func sorted()

Returns the elements of the sequence, sorted.

You can sort any sequence of elements that conform to the `Comparable` protocol by calling this method. Elements are sorted in ascending order.

The sorting algorithm is not stable. A nonstable sort may change the relative order of elements that compare equal.

Here's an example of sorting a list of students' names. Strings in Swift conform to the `Comparable` protocol, so the names are sorted in ascending order according to the less-than operator (`<`).

``````let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"``````

To sort the elements of your sequence in descending order, pass the greater-than operator (`>`) to the `sorted(by:)` method.

``````let descendingStudents = students.sorted(by: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"``````

Returns: A sorted array of the sequence's elements.

#### Declaration

`func sorted() -> [PartialRangeFrom<Bound>.Element]`

#### Declared In

`Sequence`

#### Where Element : Equatable

func contains(_:)

Returns a Boolean value indicating whether the sequence contains the given element.

This example checks to see whether a favorite actor is in an array storing a movie's cast.

``````let cast = ["Vivien", "Marlon", "Kim", "Karl"]
print(cast.contains("Marlon"))
// Prints "true"
print(cast.contains("James"))
// Prints "false"``````

`element`: The element to find in the sequence. Returns: `true` if the element was found in the sequence; otherwise, `false`.

#### Declaration

`func contains(_ element: PartialRangeFrom<Bound>.Element) -> Bool`

#### Declared In

`Sequence`
func elementsEqual(_:)

Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.

At least one of the sequences must be finite.

This example tests whether one countable range shares the same elements as another countable range and an array.

``````let a = 1...3
let b = 1...10

print(a.elementsEqual(b))
// Prints "false"
print(a.elementsEqual([1, 2, 3]))
// Prints "true"``````

`other`: A sequence to compare to this sequence. Returns: `true` if this sequence and `other` contain the same elements in the same order.

#### Declaration

`func elementsEqual<OtherSequence>(_ other: OtherSequence) -> Bool where OtherSequence : Sequence, PartialRangeFrom<Bound>.Element == OtherSequence.Element`

#### Declared In

`Sequence`
func split(_:maxSplits:omittingEmptySubsequences:)

Returns the longest possible subsequences of the sequence, in order, around elements equal to the given element.

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 at each space character (" "). 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(separator: " ")
.map(String.init))
// 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(separator: " ", maxSplits: 1)
.map(String.init))
// 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(separator: " ", omittingEmptySubsequences: false)
.map(String.init))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"``````

Parameters: separator: The element that should be split upon. maxSplits: The maximum number of times to split the sequence, or one less than the number of subsequences to return. If `maxSplits + 1` subsequences are returned, the last one is a suffix of the original sequence containing the remaining elements. `maxSplits` must be greater than or equal to zero. The default value is `Int.max`. omittingEmptySubsequences: If `false`, an empty subsequence is returned in the result for each consecutive pair of `separator` elements in the sequence and for each instance of `separator` at the start or end of the sequence. If `true`, only nonempty subsequences are returned. The default value is `true`. Returns: An array of subsequences, split from this sequence's elements.

#### Declaration

`func split(separator: PartialRangeFrom<Bound>.Element, maxSplits: Int = default, omittingEmptySubsequences: Bool = default) -> [PartialRangeFrom<Bound>.SubSequence]`

#### Declared In

`Sequence`
func starts(with:)

Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.

This example tests whether one countable range begins with the elements of another countable range.

``````let a = 1...3
let b = 1...10

print(b.starts(with: a))
// Prints "true"``````

Passing a sequence with no elements or an empty collection as `possiblePrefix` always results in `true`.

``````print(b.starts(with: []))
// Prints "true"``````

`possiblePrefix`: A sequence to compare to this sequence. Returns: `true` if the initial elements of the sequence are the same as the elements of `possiblePrefix`; otherwise, `false`. If `possiblePrefix` has no elements, the return value is `true`.

#### Declaration

`func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix) -> Bool where PossiblePrefix : Sequence, PartialRangeFrom<Bound>.Element == PossiblePrefix.Element`

#### Declared In

`Sequence`

#### Where Element : Sequence

func joined()

Returns the elements of this sequence of sequences, concatenated.

In this example, an array of three ranges is flattened so that the elements of each range can be iterated in turn.

``````let ranges = [0..<3, 8..<10, 15..<17]

// A for-in loop over 'ranges' accesses each range:
for range in ranges {
print(range)
}
// Prints "0..<3"
// Prints "8..<10"
// Prints "15..<17"

// Use 'joined()' to access each element of each range:
for index in ranges.joined() {
print(index, terminator: " ")
}
// Prints: "0 1 2 8 9 15 16"``````

Returns: A flattened view of the elements of this sequence of sequences.

#### Declaration

`func joined() -> FlattenSequence<PartialRangeFrom<Bound>>`

#### Declared In

`Sequence`
func joined(_:)

Returns the concatenated elements of this sequence of sequences, inserting the given separator between each element.

This example shows how an array of `[Int]` instances can be joined, using another `[Int]` instance as the separator:

``````let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let joined = nestedNumbers.joined(separator: [-1, -2])
print(Array(joined))
// Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]"``````

`separator`: A sequence to insert between each of this sequence's elements. Returns: The joined sequence of elements.

#### Declaration

`func joined<Separator>(separator: Separator) -> JoinedSequence<PartialRangeFrom<Bound>> where Separator : Sequence, Separator.Element == PartialRangeFrom<Bound>.Element.Element`

#### Declared In

`Sequence`

#### Where Element : StringProtocol

func joined(_:)

Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.

The following example shows how an array of strings can be joined to a single, comma-separated string:

``````let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let list = cast.joined(separator: ", ")
print(list)
// Prints "Vivien, Marlon, Kim, Karl"``````

`separator`: A string to insert between each of the elements in this sequence. The default separator is an empty string. Returns: A single, concatenated string.

#### Declaration

`func joined(separator: String = default) -> String`

#### Declared In

`Sequence`

#### Where SubSequence == AnySequence

func drop(while:)

Returns a subsequence by skipping the initial, consecutive elements that satisfy the given predicate.

The following example uses the `drop(while:)` method to skip over the positive numbers at the beginning of the `numbers` array. The result begins with the first element of `numbers` that does not satisfy `predicate`.

``````let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
let startingWithNegative = numbers.drop(while: { \$0 > 0 })
// startingWithNegative == [-2, 9, -6, 10, 1]``````

If `predicate` matches every element in the sequence, the result is an empty sequence.

`predicate`: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the result. Returns: A subsequence starting after the initial, consecutive elements that satisfy `predicate`.

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

#### Declaration

`func drop(while predicate: (PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> AnySequence<PartialRangeFrom<Bound>.Element>`

#### Declared In

`Sequence`
func dropFirst(_:)

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 sequence, 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 "[]"``````

`n`: The number of elements to drop from the beginning of the sequence. `n` must be greater than or equal to zero. Returns: A subsequence starting after the specified number of elements.

Complexity: O(1).

#### Declaration

`func dropFirst(_ n: Int) -> AnySequence<PartialRangeFrom<Bound>.Element>`

#### Declared In

`Sequence`
func dropLast(_:)

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

The sequence must be finite. If the number of elements to drop exceeds the number of elements in the sequence, 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 "[]"``````

`n`: The number of elements to drop off the end of the sequence. `n` must be greater than or equal to zero. Returns: A subsequence leaving off the specified number of elements.

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

#### Declaration

`func dropLast(_ n: Int) -> AnySequence<PartialRangeFrom<Bound>.Element>`

#### Declared In

`Sequence`
func prefix(_:)

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

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

``````let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"``````

`maxLength`: The maximum number of elements to return. The value of `maxLength` must be greater than or equal to zero. Returns: A subsequence starting at the beginning of this sequence with at most `maxLength` elements.

Complexity: O(1)

#### Declaration

`func prefix(_ maxLength: Int) -> AnySequence<PartialRangeFrom<Bound>.Element>`

#### Declared In

`Sequence`
func prefix(while:)

Returns a subsequence containing the initial, consecutive elements that satisfy the given predicate.

The following example uses the `prefix(while:)` method to find the positive numbers at the beginning of the `numbers` array. Every element of `numbers` up to, but not including, the first negative value is included in the result.

``````let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
let positivePrefix = numbers.prefix(while: { \$0 > 0 })
// positivePrefix == [3, 7, 4]``````

If `predicate` matches every element in the sequence, the resulting sequence contains every element of the sequence.

`predicate`: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the result. Returns: A subsequence of the initial, consecutive elements that satisfy `predicate`.

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

#### Declaration

`func prefix(while predicate: (PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> AnySequence<PartialRangeFrom<Bound>.Element>`

#### Declared In

`Sequence`
func split(_:omittingEmptySubsequences:whereSeparator:)

Returns the longest possible subsequences of the sequence, in order, that don't contain elements satisfying the given predicate. 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 == " " })
.map(String.init))
// 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 == " " })
.map(String.init))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"``````

The final example passes `true` for the `allowEmptySlices` parameter, so the returned array contains empty strings where spaces were repeated.

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

Parameters: maxSplits: The maximum number of times to split the sequence, or one less than the number of subsequences to return. If `maxSplits + 1` subsequences are returned, the last one is a suffix of the original sequence containing the remaining elements. `maxSplits` must be greater than or equal to zero. The default value is `Int.max`. omittingEmptySubsequences: If `false`, an empty subsequence is returned in the result for each pair of consecutive elements satisfying the `isSeparator` predicate and for each element at the start or end of the sequence satisfying the `isSeparator` predicate. If `true`, only nonempty subsequences are returned. The default value is `true`. isSeparator: A closure that returns `true` if its argument should be used to split the sequence; otherwise, `false`. Returns: An array of subsequences, split from this sequence's elements.

#### Declaration

`func split(maxSplits: Int = default, omittingEmptySubsequences: Bool = default, whereSeparator isSeparator: (PartialRangeFrom<Bound>.Element) throws -> Bool) rethrows -> [AnySequence<PartialRangeFrom<Bound>.Element>]`

#### Declared In

`Sequence`
func suffix(_:)

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

The sequence must be finite. If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.

``````let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"``````

`maxLength`: The maximum number of elements to return. The value of `maxLength` must be greater than or equal to zero. Complexity: O(n), where n is the length of the sequence.

#### Declaration

`func suffix(_ maxLength: Int) -> AnySequence<PartialRangeFrom<Bound>.Element>`

#### Declared In

`Sequence`