struct EnumeratedIterator<Base : IteratorProtocol>
Inheritance 
IteratorProtocol, Sequence
View Protocol Hierarchy →


Associated Types 
Element = (offset: Int, element: Base.Element)
The type of element returned by 
Import  import Swift 
Instance Variables
A sequence containing the same elements as this sequence,
but on which some operations, such as map
and filter
, are
implemented lazily.
See Also: LazySequenceProtocol
, LazySequence
Declaration
var lazy: LazySequence<EnumeratedIterator<Base>> { get }
Declared In
Sequence
Returns a value less than or equal to the number of elements in the sequence, nondestructively.
Complexity: O(n)
Declaration
var underestimatedCount: Int { get }
Declared In
Sequence
Instance Methods
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
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: ((offset: Int, element: Base.Element)) throws > Bool) rethrows > Bool
Declared In
Sequence
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() > EnumeratedIterator<Base>.SubSequence
Declared In
Sequence
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<(offset: Int, element: Base.Element)>
Declared In
Sequence
Returns a subsequence containing all but the last element of the sequence.
The sequence must be finite. If the sequence has no elements, the result is an empty subsequence.
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() > EnumeratedIterator<Base>.SubSequence
Declared In
Sequence
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<(offset: Int, element: Base.Element)>
Declared In
Sequence
Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements, 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 alwaystrue
. (Reflexivity)areEquivalent(a, b)
impliesareEquivalent(b, a)
. (Symmetry) If
areEquivalent(a, b)
andareEquivalent(b, c)
are bothtrue
, thenareEquivalent(a, c)
is alsotrue
. (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.
See Also: elementsEqual(_:)
Declaration
func elementsEqual<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence, by areEquivalent: ((offset: Int, element: Base.Element), (offset: Int, element: Base.Element)) throws > Bool) rethrows > Bool
Declared In
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".characters.enumerated() {
print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"
When enumerating a collection, the integer part of each pair is a counter
for the enumeration, not necessarily the index of the paired value.
These counters can only be used as indices 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 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.characters.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<EnumeratedIterator<Base>>
Declared In
Sequence
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.characters.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"
shouldInclude
: 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 includeElement
allowed.
Declaration
func filter(_ isIncluded: ((offset: Int, element: Base.Element)) throws > Bool) rethrows > [(offset: Int, element: Base.Element)]
Declared In
Sequence
Returns the first element of the sequence that satisfies the given predicate or nil if no such element is found.
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 match or nil
if there was no match.
Declaration
func first(where predicate: ((offset: Int, element: Base.Element)) throws > Bool) rethrows > (offset: Int, element: Base.Element)?
Declared In
Sequence
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
flatMap
with a transformation that returns an optional Int
value.
let possibleNumbers = ["1", "2", "three", "///4///", "5"]
let mapped: [Int?] = numbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]
let flatMapped: [Int] = numbers.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 nonnil
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: ((offset: Int, element: Base.Element)) throws > ElementOfResult?) rethrows > [ElementOfResult]
Declared In
Sequence
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(count: $0, repeatedValue: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
let flatMapped = numbers.flatMap { Array(count: $0, repeatedValue: $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.
See Also: joined()
, map(_:)
Declaration
func flatMap<SegmentOfResult : Sequence>(_ transform: ((offset: Int, element: Base.Element)) throws > SegmentOfResult) rethrows > [SegmentOfResult.Iterator.Element]
Declared In
Sequence
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.
body
: A closure that takes an element of the sequence as a
parameter.
Declaration
func forEach(_ body: ((offset: Int, element: Base.Element)) throws > Swift.Void) rethrows
Declared In
Sequence
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 alwaysfalse
. (Irreflexivity) If
areInIncreasingOrder(a, b)
andareInIncreasingOrder(b, c)
are bothtrue
, thenareInIncreasingOrder(a, c)
is alsotrue
. (Transitive comparability)  Two elements are incomparable if neither is ordered before the other
according to the predicate. If
a
andb
are incomparable, andb
andc
are incomparable, thena
andc
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.
See Also: lexicographicallyPrecedes(_:)
Declaration
func lexicographicallyPrecedes<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence, by areInIncreasingOrder: ((offset: Int, element: Base.Element), (offset: Int, element: Base.Element)) throws > Bool) rethrows > Bool
Declared In
Sequence
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.lowercaseString }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.characters.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: ((offset: Int, element: Base.Element)) throws > T) rethrows > [T]
Declared In
Sequence
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 alwaysfalse
. (Irreflexivity) If
areInIncreasingOrder(a, b)
andareInIncreasingOrder(b, c)
are bothtrue
, thenareInIncreasingOrder(a, c)
is alsotrue
. (Transitive comparability)  Two elements are incomparable if neither is ordered before the other
according to the predicate. If
a
andb
are incomparable, andb
andc
are incomparable, thena
andc
are also incomparable. (Transitive incomparability)
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))"
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
.
See Also: max()
Declaration
@warn_unqualified_access
func max(by areInIncreasingOrder: ((offset: Int, element: Base.Element), (offset: Int, element: Base.Element)) throws > Bool) rethrows > (offset: Int, element: Base.Element)?
Declared In
Sequence
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 alwaysfalse
. (Irreflexivity) If
areInIncreasingOrder(a, b)
andareInIncreasingOrder(b, c)
are bothtrue
, thenareInIncreasingOrder(a, c)
is alsotrue
. (Transitive comparability)  Two elements are incomparable if neither is ordered before the other
according to the predicate. If
a
andb
are incomparable, andb
andc
are incomparable, thena
andc
are also incomparable. (Transitive incomparability)
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))"
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
.
See Also: min()
Declaration
@warn_unqualified_access
func min(by areInIncreasingOrder: ((offset: Int, element: Base.Element), (offset: Int, element: Base.Element)) throws > Bool) rethrows > (offset: Int, element: Base.Element)?
Declared In
Sequence
Advances to the next element and returns it, or nil
if no next element
exists.
Once nil
has been returned, all subsequent calls return nil
.
Declaration
mutating func next() > (offset: Int, element: Base.Element)?
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<(offset: Int, element: Base.Element)>
Declared In
Sequence
Returns the result of calling the given combining closure with each element of this sequence and an accumulating value.
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 addTwo: (Int, Int) > Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10
When numbers.reduce(_:_:)
is called, the
following steps occur:
 The
nextPartialResult
closure is called with the initial result and 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.
Parameters:
initialResult: the initial accumulating value.
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.
Declaration
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, (offset: Int, element: Base.Element)) throws > Result) rethrows > Result
Declared In
Sequence
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() > [(offset: Int, element: Base.Element)]
Declared In
Sequence
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 alwaysfalse
. (Irreflexivity) If
areInIncreasingOrder(a, b)
andareInIncreasingOrder(b, c)
are bothtrue
, thenareInIncreasingOrder(a, c)
is alsotrue
. (Transitive comparability)  Two elements are incomparable if neither is ordered before the other
according to the predicate. If
a
andb
are incomparable, andb
andc
are incomparable, thena
andc
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 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"]"
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.
See Also: sorted()
Declaration
func sorted(by areInIncreasingOrder: ((offset: Int, element: Base.Element), (offset: Int, element: Base.Element)) > Bool) > [(offset: Int, element: Base.Element)]
Declared In
Sequence
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.characters.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.characters.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.characters.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: ((offset: Int, element: Base.Element)) throws > Bool) rethrows > [AnySequence<(offset: Int, element: Base.Element)>]
Declared In
Sequence
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 alwaystrue
. (Reflexivity)areEquivalent(a, b)
impliesareEquivalent(b, a)
. (Symmetry) If
areEquivalent(a, b)
andareEquivalent(b, c)
are bothtrue
, thenareEquivalent(a, c)
is alsotrue
. (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
.
See Also: starts(with:)
Declaration
func starts<PossiblePrefix where PossiblePrefix : Sequence, PossiblePrefix.Iterator.Element == Iterator.Element>(with possiblePrefix: PossiblePrefix, by areEquivalent: ((offset: Int, element: Base.Element), (offset: Int, element: Base.Element)) throws > Bool) rethrows > Bool
Declared In
Sequence
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<(offset: Int, element: Base.Element)>
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 Iterator == Self, Self : IteratorProtocol
Returns an iterator over the elements of this sequence.
Declaration
func makeIterator() > EnumeratedIterator<Base>
Declared In
Sequence
The iterator for
EnumeratedSequence
.An instance of
EnumeratedIterator
wraps a base iterator and yields successiveInt
values, starting at zero, along with the elements of the underlying base iterator. The following example enumerates the elements of an array:To create an instance of
EnumeratedIterator
, callenumerated().makeIterator()
on a sequence or collection.