struct ReversedCollection
A collection that presents the elements of its base collection in reverse order.
Inheritance  BidirectionalCollection, Sequence 

Associated Types 
public typealias Element = Base.Element

Nested Types  ReversedCollection.Iterator, ReversedCollection.Index 
Note: This type is the result of
x.reversed()
wherex
is a collection having bidirectional indices.
The reversed()
method is always lazy when applied to a collection
with bidirectional indices, but does not implicitly confer
laziness on algorithms applied to its result. In other words, for
ordinary collections c
having bidirectional indices:
Initializers
Creates a new index into a reversed collection for the position before the specified index.
When you create an index into a reversed collection using base
, an
index from the underlying collection, the resulting index is the
position of the element before the element referenced by base
. The
following example creates a new ReversedIndex
from the index of the
"a"
character in a string's character view.
let name = "Horatio"
let aIndex = name.firstIndex(of: "a")!
// name[aIndex] == "a"
let reversedName = name.reversed()
let i = ReversedIndex<String>(aIndex)
// reversedName[i] == "r"
The element at the position created using ReversedIndex<...>(aIndex)
is
"r"
, the character before "a"
in the name
string.
 Parameter base: The position after the element to create an index for.
Declaration
@inlinable public init(_ base: Base.Index)
Instance Variables
The position after this position in the underlying collection.
To find the position that corresponds with this index in the original,
underlying collection, use that collection's index(before:)
method
with the base
property.
The following example declares a function that returns the index of the
last even number in the passed array, if one is found. First, the
function finds the position of the last even number as a ReversedIndex
in a reversed view of the array of numbers. Next, the function calls the
array's index(before:)
method to return the correct position in the
passed array.
func indexOfLastEven(_ numbers: [Int]) > Int? {
let reversedNumbers = numbers.reversed()
guard let i = reversedNumbers.firstIndex(where: { $0 % 2 == 0 })
else { return nil }
return numbers.index(before: i.base)
}
let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
if let lastEven = indexOfLastEven(numbers) {
print("Last even number: \(numbers[lastEven])")
}
// Prints "Last even number: 40"
Declaration
let base: Base.Index
The collection's "past the end" positionthat 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 halfopen 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: ReversedCollection<Base>.Index
The last 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 lastNumber = numbers.last {
print(lastNumber)
}
// Prints "50"
Complexity: O(1)
Declaration
var last: Self.Element?
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<Self>
The position of the first element in a nonempty collection.
If the collection is empty, startIndex
is equal to endIndex
.
Declaration
var startIndex: ReversedCollection<Base>.Index
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 ofCollection.underestimatedCount
.
Declaration
var underestimatedCount: Int
Subscripts
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 theendIndex
property.
Complexity: O(1)
Declaration
@inlinable public subscript(position: ReversedCollection<Base>.Index) > ReversedCollection<Base>.Element
Instance Methods
Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.
The following code uses this method to test whether all the names in an array have at least five characters:
let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
// allHaveAtLeastFive == true
 Parameter 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.
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func allSatisfy(_ predicate: (Self.Element) throws > Bool) rethrows > Bool
Returns an array containing the nonnil
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]
 Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.
Complexity: O(m + n), where n is the length of this sequence and m is the length of the result.
Declaration
@inlinable public func compactMap<ElementOfResult>(_ transform: (Self.Element) throws > ElementOfResult?) rethrows > [ElementOfResult]
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
}
}
// 'hadError' == true
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
 Parameter 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.
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func contains(where predicate: (Self.Element) throws > Bool) rethrows > Bool
Returns the difference needed to produce this collection's ordered elements from the given collection, using the given predicate as an equivalence test.
This function does not infer element moves. If you need to infer moves,
call the inferringMoves()
method on the resulting difference.
Complexity: Worst case performance is O(n * m), where n is the count of this collection and m is
other.count
. You can expect faster execution when the collections share many common elements.
Declaration
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func difference<C>(from other: C, by areEquivalent: (C.Element, Self.Element) > Bool) > CollectionDifference<Self.Element> where C: BidirectionalCollection, Self.Element == C.Element
Declaration
@inlinable public func distance(from start: Self.Index, to end: Self.Index) > Int
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: ReversedCollection<Base>.Index, to end: ReversedCollection<Base>.Index) > Int
Returns a sequence 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.
 Parameter 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.
Complexity: O(k), where k is the number of elements to drop from the beginning of the sequence.
Declaration
@inlinable public func drop(while predicate: (Self.Element) throws > Bool) rethrows > DropWhileSequence<Self>
Returns a sequence 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 sequence.
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 sequence.
k
must be greater than or equal to zero.
Complexity: O(1), with O(k) deferred to each iteration of the result, where k is the number of elements to drop from the beginning of the sequence.
Declaration
@inlinable public func dropFirst(_ k: Int = 1) > DropFirstSequence<Self>
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(k), where k is the number of elements to drop.
Declaration
@inlinable public func dropLast(_ k: Int) > Self.SubSequence
Returns a sequence 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 sequence.
let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"
 Parameter n: The number of elements to drop off the end of the
sequence.
n
must be greater than or equal to zero.
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func dropLast(_ k: Int = 1) > [Self.Element]
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:
Complexity: O(m), where m is the lesser of the length of the sequence and the length of
other
.
Declaration
@inlinable public func elementsEqual<OtherSequence>(_ other: OtherSequence, by areEquivalent: (Self.Element, OtherSequence.Element) throws > Bool) rethrows > Bool where OtherSequence: Sequence
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 zerobased,
integerindexed 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: [Set<String>.Index] = []
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"
Complexity: O(1)
Declaration
@inlinable public func enumerated() > EnumeratedSequence<Self>
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"]"
 Parameter 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.
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func filter(_ isIncluded: (Self.Element) throws > Bool) rethrows > [Self.Element]
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."
 Parameter 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.
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func first(where predicate: (Self.Element) throws > Bool) rethrows > Self.Element?
Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.
Use this method to receive a singlelevel 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())
.
 Parameter transform: A closure that accepts an element of this sequence as its argument and returns a sequence or collection.
Complexity: O(m + n), where n is the length of this sequence and m is the length of the result.
Declaration
@inlinable public func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws > SegmentOfResult) rethrows > [SegmentOfResult.Element] where SegmentOfResult: Sequence
Declaration
@available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value") public func flatMap<ElementOfResult>(_ transform: (Self.Element) throws > ElementOfResult?) rethrows > [ElementOfResult]
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:
 You cannot use a
break
orcontinue
statement to exit the current call of thebody
closure or skip subsequent calls.  Using the
return
statement in thebody
closure will exit only from the current call tobody
, not from any outer scope, and won't skip subsequent calls.
 Parameter body: A closure that takes an element of the sequence as a parameter.
Declaration
@inlinable public func forEach(_ body: (Self.Element) throws > Void) rethrows
Replaces the given index with its predecessor.
 Parameter i: A valid index of the collection.
i
must be greater thanstartIndex
.
Declaration
@inlinable public func formIndex(before i: inout Self.Index)
Declaration
@inlinable public func index(_ i: Self.Index, offsetBy distance: Int) > Self.Index
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 ofdistance
.
Declaration
@inlinable public func index(_ i: ReversedCollection<Base>.Index, offsetBy n: Int) > ReversedCollection<Base>.Index
Declaration
@inlinable public func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) > Self.Index?
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 ofdistance
.
Declaration
@inlinable public func index(_ i: ReversedCollection<Base>.Index, offsetBy n: Int, limitedBy limit: ReversedCollection<Base>.Index) > ReversedCollection<Base>.Index?
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 thanendIndex
.
Declaration
@inlinable public func index(after i: ReversedCollection<Base>.Index) > ReversedCollection<Base>.Index
Returns the position immediately before the given index.
 Parameter i: A valid index of the collection.
i
must be greater thanstartIndex
.
Declaration
@inlinable public func index(before i: ReversedCollection<Base>.Index) > ReversedCollection<Base>.Index
Returns the last element of the sequence that satisfies the given predicate.
This example uses the last(where:)
method to find the last
negative number in an array of integers:
let numbers = [3, 7, 4, 2, 9, 6, 10, 1]
if let lastNegative = numbers.last(where: { $0 < 0 }) {
print("The last negative number is \(lastNegative).")
}
// Prints "The last negative number is 6."
 Parameter 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.
Complexity: O(n), where n is the length of the collection.
Declaration
@inlinable public func last(where predicate: (Self.Element) throws > Bool) rethrows > Self.Element?
Returns the index of the last element in the collection that matches 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. This example finds the index of the last name that
begins with the letter A:
let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.lastIndex(where: { $0.hasPrefix("A") }) {
print("\(students[i]) starts with 'A'!")
}
// Prints "Akosua 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 lastIndex(where predicate: (Self.Element) throws > Bool) rethrows > Self.Index?
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:
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.
Complexity: O(m), where m is the lesser of the length of the sequence and the length of
other
.
Declaration
@inlinable public func lexicographicallyPrecedes<OtherSequence>(_ other: OtherSequence, by areInIncreasingOrder: (Self.Element, Self.Element) throws > Bool) rethrows > Bool where OtherSequence: Sequence, Self.Element == OtherSequence.Element
Returns an iterator over the elements of this sequence.
Declaration
@inlinable public func makeIterator() > ReversedCollection<Base>.Iterator
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.
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func map<T>(_ transform: (Self.Element) throws > T) rethrows > [T]
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:
This example shows how to use the max(by:)
method on a
dictionary to find the keyvalue 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))"
 Parameter areInIncreasingOrder: A predicate that returns
true
if its first argument should be ordered before its second argument; otherwise,false
.
Complexity: O(n), where n is the length of the sequence.
Declaration
@warn_unqualified_access @inlinable public func max(by areInIncreasingOrder: (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.
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:
This example shows how to use the min(by:)
method on a
dictionary to find the keyvalue 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))"
 Parameter areInIncreasingOrder: A predicate that returns
true
if its first argument should be ordered before its second argument; otherwise,false
.
Complexity: O(n), where n is the length of the sequence.
Declaration
@warn_unqualified_access @inlinable public func min(by areInIncreasingOrder: (Self.Element, Self.Element) throws > Bool) rethrows > Self.Element?
Returns a sequence, 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]"
 Parameter maxLength: The maximum number of elements to return. The
value of
maxLength
must be greater than or equal to zero.
Complexity: O(1)
Declaration
@inlinable public func prefix(_ maxLength: Int) > PrefixSequence<Self>
Returns a sequence 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.
 Parameter 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.
Complexity: O(k), where k is the length of the result.
Declaration
@inlinable public func prefix(while predicate: (Self.Element) throws > Bool) rethrows > [Self.Element]
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:
 The
nextPartialResult
closure is called withinitialResult
0
in this caseand the first element ofnumbers
, returning the sum:1
.  The closure is called again repeatedly with the previous call's return value and each element of the sequence.
 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(_:_:)
.
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Self.Element) throws > Result) rethrows > Result
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 copyonwrite 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:
 The
updateAccumulatingResult
closure is called with the initial accumulating value[:]
in this caseand the first character ofletters
, modifying the accumulating value by setting1
for the key"a"
.  The closure is called again repeatedly with the updated accumulating value and each element of the sequence.
 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:_:)
.
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Self.Element) throws > ()) rethrows > Result
Reversing a reversed collection returns the original collection.
Complexity: O(1)
Declaration
@available(swift 4.2) @inlinable public func reversed() > Base
Returns a view presenting the elements of the collection in reverse order.
You can reverse a collection without allocating new space for its
elements by calling this reversed()
method. A ReversedCollection
instance wraps an underlying collection and provides access to its
elements in reverse order. This example prints the characters of a
string in reverse order:
let word = "Backwards"
for char in word.reversed() {
print(char, terminator: "")
}
// Prints "sdrawkcaB"
If you need a reversed collection of the same type, you may be able to
use the collection's sequencebased or collectionbased initializer. For
example, to get the reversed version of a string, reverse its
characters and initialize a new String
instance from the result.
let reversedWord = String(word.reversed())
print(reversedWord)
// Prints "sdrawkcaB"
Complexity: O(1)
Declaration
@inlinable public func reversed() > ReversedCollection<Self>
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.
Declaration
@inlinable public func reversed() > [Self.Element]
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 is equivalent to calling shuffled(using:)
, passing in the
system's default random generator.
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func shuffled() > [Self.Element]
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]
 Parameter generator: The random number generator to use when shuffling the sequence.
Complexity: O(n), where n is the length of the sequence.
Note: The algorithm used to shuffle a sequence may change in a future version of Swift. If you're passing a generator that results in the same shuffled order 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 shuffled<T>(using generator: inout T) > [Self.Element] where T: RandomNumberGenerator
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 should be ordered before the second. The
elements of the resulting array are ordered according to the given
predicate.
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 greaterthan 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 lessthan operator (<
) as the predicate.
print(students.sorted())
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
print(students.sorted(by: <))
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
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:
The sorting algorithm is not guaranteed to be stable. A stable sort
preserves the relative order of elements for which
areInIncreasingOrder
does not establish an order.
 Parameter areInIncreasingOrder: A predicate that returns
true
if its first argument should be ordered before its second argument; otherwise,false
.
Complexity: O(n log n), where n is the length of the sequence.
Declaration
@inlinable public func sorted(by areInIncreasingOrder: (Self.Element, Self.Element) throws > Bool) rethrows > [Self.Element]
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!"]"
Complexity: O(n), where n is the length of the sequence.
Declaration
@inlinable public func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws > Bool) rethrows > [ArraySlice<Self.Element>]
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:
Complexity: O(m), where m is the lesser of the length of the sequence and the length of
possiblePrefix
.
Declaration
@inlinable public func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix, by areEquivalent: (Self.Element, PossiblePrefix.Element) throws > Bool) rethrows > Bool where PossiblePrefix: Sequence
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 the entire 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.
maxLength
must be greater than or equal to zero.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is equal tomaxLength
.
Declaration
@inlinable public func suffix(_ maxLength: Int) > Self.SubSequence
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]"
 Parameter 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
@inlinable public func suffix(_ maxLength: Int) > [Self.Element]
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<Self.Element>) throws > R) rethrows > R?
Valid indices consist of the position of every element and a "past the end" position that's not valid for use as a subscript.