struct
Slice
<
Base
>
Inheritance |
BidirectionalCollection, Collection, LazyCollectionProtocol, LazySequenceProtocol, MutableCollection, RandomAccessCollection, RangeReplaceableCollection, Sequence
View Protocol Hierarchy →
|
---|---|
Associated Types |
A type that represents a position in the collection. Valid indices consist of the position of every element and a "past the end" position that's not valid for use as a subscript argument.
A type that represents the indices that are valid for subscripting the collection, in ascending order.
A type representing the sequence's elements.
A type that represents a subsequence of some of the sequence's elements.
A type that provides the sequence's iteration interface and encapsulates its iteration state. |
Import |
|
Initializers
Creates a new, empty collection.
Declaration
init
()
Creates a new instance of a collection containing the elements of a sequence.
elements
: The sequence of elements for the new collection.
elements
must be finite.
Declaration
init
<
S
>
(
_
elements
:
S
)
Declared In
Slice
, RangeReplaceableCollection
Creates a view into the given collection that allows access to elements within the specified range.
It is unusual to need to call this method directly. Instead, create a slice of a collection by using the collection's range-based subscript or by using methods that return a subsequence.
let
singleDigits
=
0
...
9
let
subSequence
=
singleDigits
.
dropFirst
(
5
)
(
Array
(
subSequence
))
// Prints "[5, 6, 7, 8, 9]"
In this example, the expression singleDigits.dropFirst(5))
is
equivalent to calling this initializer with singleDigits
and a
range covering the last five items of singleDigits.indices
.
Parameters: base: The collection to create a view into. bounds: The range of indices to allow access to in the new slice.
Declaration
init
(
base
:
Base
,
bounds
:
Range
<
Base
.
Index
>
)
Creates a new collection containing the specified number of a single, repeated value.
The following example creates an array initialized with five strings containing the letter Z.
let
fiveZs
=
Array
(
repeating
:
"Z"
,
count
:
5
)
(
fiveZs
)
// Prints "["Z", "Z", "Z", "Z", "Z"]"
Parameters:
repeatedValue: The element to repeat.
count: The number of times to repeat the value passed in the
repeating
parameter. count
must be zero or greater.
Declaration
init
(
repeating
repeatedValue
:
Base
.
Element
,
count
:
Int
)
Declared In
Slice
, RangeReplaceableCollection
Instance Variables
The underlying collection of the slice.
You can use a slice's base
property to access its base collection. The
following example declares singleDigits
, a range of single digit
integers, and then drops the first element to create a slice of that
range, singleNonZeroDigits
. The base
property of the slice is equal
to singleDigits
.
let
singleDigits
=
0
..
<
10
let
singleNonZeroDigits
=
singleDigits
.
dropFirst
()
// singleNonZeroDigits is a Slice<Range<Int>>
(
singleNonZeroDigits
.
count
)
// Prints "9"
prints
(
singleNonZeroDigits
.
base
.
count
)
// Prints "10"
(
singleDigits
==
singleNonZeroDigits
.
base
)
// Prints "true"
Declaration
var
base
:
Base
{
get
}
The number of elements in the collection.
To check whether a collection is empty, use its isEmpty
property
instead of comparing count
to zero. Unless the collection guarantees
random-access performance, calculating count
can be an O(n)
operation.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the length
of the collection.
Declaration
var
count
:
Int
{
get
}
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
The collection's "past the end" position---that is, the position one greater than the last valid subscript argument.
When you need a range that includes the last element of a collection, use
the half-open range operator (..<
) with endIndex
. The ..<
operator
creates a range that doesn't include the upper bound, so it's always
safe to use with endIndex
. For example:
let
numbers
= [
10
,
20
,
30
,
40
,
50
]
if
let
index
=
numbers
.
firstIndex
(
of
:
30
) {
(
numbers
[
index
..
<
numbers
.
endIndex
])
}
// Prints "[30, 40, 50]"
If the collection is empty, endIndex
is equal to startIndex
.
Declaration
var
endIndex
:
Base
.
Index
{
get
}
The first element of the collection.
If the collection is empty, the value of this property is nil
.
let
numbers
= [
10
,
20
,
30
,
40
,
50
]
if
let
firstNumber
=
numbers
.
first
{
(
firstNumber
)
}
// Prints "10"
Declaration
var
first
:
Slice
<
Base
>
.
Element
? {
get
}
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
The indices that are valid for subscripting the collection, in ascending order.
A collection's indices
property can hold a strong reference to the
collection itself, causing the collection to be nonuniquely referenced.
If you mutate the collection while iterating over its indices, a strong
reference can result in an unexpected copy of the collection. To avoid
the unexpected copy, use the index(after:)
method starting with
startIndex
to produce indices instead.
var
c
=
MyFancyCollection
([
10
,
20
,
30
,
40
,
50
])
var
i
=
c
.
startIndex
while
i
!=
c
.
endIndex
{
c
[
i
] /=
5
i
=
c
.
index
(
after
:
i
)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])
Declaration
var
indices
:
Base
.
Indices
{
get
}
A Boolean value indicating whether the collection is empty.
When you need to check whether your collection is empty, use the
isEmpty
property instead of checking that the count
property is
equal to zero. For collections that don't conform to
RandomAccessCollection
, accessing the count
property iterates
through the elements of the collection.
let
horseName
=
"Silver"
if
horseName
.
isEmpty
{
(
"I've been through the desert on a horse with no name."
)
}
else
{
(
"Hi ho, \(
horseName
)!"
)
}
// Prints "Hi ho, Silver!")
Complexity: O(1)
Declaration
var
isEmpty
:
Bool
{
get
}
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
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
{
(
lastNumber
)
}
// Prints "50"
Declaration
var
last
:
Slice
<
Base
>
.
Element
? {
get
}
Declared In
RandomAccessCollection
, BidirectionalCollection
Declaration
var
lazy
:
LazyCollection
<
Slice
<
Base
>
.
Elements
>
{
get
}
Declared In
LazyCollectionProtocol
The position of the first element in a nonempty collection.
If the collection is empty, startIndex
is equal to endIndex
.
Declaration
var
startIndex
:
Base
.
Index
{
get
}
A value less than or equal to the number of elements in the collection.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the length
of the collection.
Declaration
var
underestimatedCount
:
Int
{
get
}
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
6 inherited items hidden. (Show all)
Subscripts
Declaration
subscript
(
x
: (
UnboundedRange_
) -
>
()) -
>
Slice
<
Base
>
.
SubSequence
{
get
}
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Accesses a contiguous subrange of the collection's elements.
The accessed slice uses the same indices for the same elements as the
original collection. Always use the slice's startIndex
property
instead of assuming that its indices start at a particular value.
This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array.
let
streets
= [
"Adams"
,
"Bryant"
,
"Channing"
,
"Douglas"
,
"Evarts"
]
let
streetsSlice
=
streets
[
2
..
<
streets
.
endIndex
]
(
streetsSlice
)
// Prints "["Channing", "Douglas", "Evarts"]"
let
index
=
streetsSlice
.
firstIndex
(
of
:
"Evarts"
)
// 4
streets
[
index
!] =
"Eustace"
(
streets
[
index
!])
// Prints "Eustace"
bounds
: A range of the collection's indices. The bounds of
the range must be valid indices of the collection.
Declaration
Declared In
Slice
, MutableCollection
Accesses a contiguous subrange of the collection's elements.
For example, using a PartialRangeFrom
range expression with an array
accesses the subrange from the start of the range expression until the
end of the array.
let
streets
= [
"Adams"
,
"Bryant"
,
"Channing"
,
"Douglas"
,
"Evarts"
]
let
streetsSlice
=
streets
[
2
..
<
5
]
(
streetsSlice
)
// ["Channing", "Douglas", "Evarts"]
The accessed slice uses the same indices for the same elements as the
original collection. This example searches streetsSlice
for one of the
strings in the slice, and then uses that index in the original array.
let
index
=
streetsSlice
.
firstIndex
(
of
:
"Evarts"
)!
// 4
(
streets
[
index
])
// "Evarts"
Always use the slice's startIndex
property instead of assuming that its
indices start at a particular value. Attempting to access an element by
using an index outside the bounds of the slice may result in a runtime
error, even if that index is valid for the original collection.
(
streetsSlice
.
startIndex
)
// 2
(
streetsSlice
[
2
])
// "Channing"
(
streetsSlice
[
0
])
// error: Index out of bounds
bounds
: A range of the collection's indices. The bounds of
the range must be valid indices of the collection.
Complexity: O(1)
Declaration
Accesses the element at the specified position.
For example, you can replace an element of an array by using its subscript.
var
streets
= [
"Adams"
,
"Bryant"
,
"Channing"
,
"Douglas"
,
"Evarts"
]
streets
[
1
] =
"Butler"
(
streets
[
1
])
// Prints "Butler"
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.
position
: The position of the element to access. position
must be a valid index of the collection that is not equal to the
endIndex
property.
Declaration
subscript
(
index
:
Slice
<
Base
>
.
Index
) -
>
Base
.
Element
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"
]
(
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.
position
: The position of the element to access. position
must be a valid index of the collection that is not equal to the
endIndex
property.
Complexity: O(1)
Declaration
subscript
(
index
:
Slice
<
Base
>
.
Index
) -
>
Base
.
Element
{
get
}
Accesses the contiguous subrange of the collection's elements specified by a range expression.
The range expression is converted to a concrete subrange relative to this
collection. For example, using a PartialRangeFrom
range expression
with an array accesses the subrange from the start of the range
expression until the end of the array.
let
streets
= [
"Adams"
,
"Bryant"
,
"Channing"
,
"Douglas"
,
"Evarts"
]
let
streetsSlice
=
streets
[
2
...]
(
streetsSlice
)
// ["Channing", "Douglas", "Evarts"]
The accessed slice uses the same indices for the same elements as the
original collection uses. This example searches streetsSlice
for one
of the strings in the slice, and then uses that index in the original
array.
let
index
=
streetsSlice
.
firstIndex
(
of
:
"Evarts"
)
// 4
(
streets
[
index
!])
// "Evarts"
Always use the slice's startIndex
property instead of assuming that its
indices start at a particular value. Attempting to access an element by
using an index outside the bounds of the slice's indices may result in a
runtime error, even if that index is valid for the original collection.
(
streetsSlice
.
startIndex
)
// 2
(
streetsSlice
[
2
])
// "Channing"
(
streetsSlice
[
0
])
// error: Index out of bounds
bounds
: A range of the collection's indices. The bounds of
the range must be valid indices of the collection.
Complexity: O(1)
Declaration
subscript
<
R
>
(
r
:
R
) -
>
Slice
<
Base
>
.
SubSequence
where
R
:
RangeExpression
,
Slice
<
Base
>
.
Index
==
R
.
Bound
{
get
}
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
2 inherited items hidden. (Show all)
Instance Methods
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Adds an element to the end of the collection.
If the collection does not have sufficient capacity for another element,
additional storage is allocated before appending newElement
. The
following example adds a new number to an array of integers:
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
append
(
100
)
(
numbers
)
// Prints "[1, 2, 3, 4, 5, 100]"
newElement
: The element to append to the collection.
Complexity: O(1) on average, over many additions to the same collection.
Declaration
mutating
func
append
(
_
newElement
:
Slice
<
Base
>
.
Element
)
Declared In
RangeReplaceableCollection
Adds the elements of a sequence or collection to the end of this collection.
The collection being appended to allocates any additional necessary storage to hold the new elements.
The following example appends the elements of a Range<Int>
instance to
an array of integers:
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
append
(
contentsOf
:
10
...
15
)
(
numbers
)
// Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
newElements
: The elements to append to the collection.
Complexity: O(n), where n is the length of the resulting collection.
Declaration
mutating
func
append
<
S
>
(
contentsOf
newElements
:
S
)
Declared In
RangeReplaceableCollection
Returns the non-nil
results of mapping the given transformation over
this collection.
Use this method to receive a collection of nonoptional values when your transformation produces an optional value.
transform
: A closure that accepts an element of this
collection as its argument and returns an optional value.
Complexity: O(1)
Declaration
func
compactMap
<
ElementOfResult
>
(
_
transform
: @
escaping
(
Slice
<
Base
>
.
Elements
.
Element
) -
>
ElementOfResult
?) -
>
LazyMapCollection
<
LazyFilterCollection
<
LazyMapCollection
<
Slice
<
Base
>
.
Elements
,
ElementOfResult
?
>
>
,
ElementOfResult
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Returns the distance between two indices.
Unless the collection conforms to the BidirectionalCollection
protocol,
start
must be less than or equal to end
.
Parameters:
start: A valid index of the collection.
end: Another valid index of the collection. If end
is equal to
start
, the result is zero.
Returns: The distance between start
and end
. The result can be
negative only if the collection conforms to the
BidirectionalCollection
protocol.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the
resulting distance.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Returns the distance between two indices.
Unless the collection conforms to the BidirectionalCollection
protocol,
start
must be less than or equal to end
.
Parameters:
start: A valid index of the collection.
end: Another valid index of the collection. If end
is equal to
start
, the result is zero.
Returns: The distance between start
and end
. The result can be
negative only if the collection conforms to the
BidirectionalCollection
protocol.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the
resulting distance.
Declaration
Declared In
Slice
, RandomAccessCollection
, BidirectionalCollection
Deprecated: all index distances are now of type Int.
Declaration
func
distance
<
T
>
(
from
start
:
Slice
<
Base
>
.
Index
,
to
end
:
Slice
<
Base
>
.
Index
) -
>
T
where
T
:
BinaryInteger
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Returns a lazy collection that skips any initial elements that satisfy
predicate
.
predicate
: A closure that takes an element of the collection
as its argument and returns true
if the element should be skipped or
false
otherwise. Once predicate
returns false
it will not be
called again.
Declaration
func
drop
(
while
predicate
: @
escaping
(
Slice
<
Base
>
.
Elements
.
Element
) -
>
Bool
) -
>
LazyDropWhileCollection
<
Slice
<
Base
>
.
Elements
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
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
]
(
numbers
.
dropFirst
())
// Prints "[2, 3, 4, 5]"
If the sequence has no elements, the result is an empty subsequence.
let
empty
: [
Int
] = []
(
empty
.
dropFirst
())
// Prints "[]"
Returns: A subsequence starting after the first element of the sequence.
Complexity: O(1)
Declaration
func
dropFirst
() -
>
Slice
<
Base
>
.
SubSequence
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, 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 collection, the result is an empty subsequence.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
dropFirst
(
2
))
// Prints "[3, 4, 5]"
(
numbers
.
dropFirst
(
10
))
// Prints "[]"
n
: The number of elements to drop from the beginning of
the collection. n
must be greater than or equal to zero.
Returns: A subsequence starting after the specified number of
elements.
Complexity: O(n), where n is the number of elements to drop from the beginning of the collection.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Returns a subsequence containing all but the last element of the sequence.
The sequence must be finite.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
dropLast
())
// Prints "[1, 2, 3, 4]"
If the sequence has no elements, the result is an empty subsequence.
let
empty
: [
Int
] = []
(
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
() -
>
Slice
<
Base
>
.
SubSequence
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
]
(
numbers
.
dropLast
(
2
))
// Prints "[1, 2, 3]"
(
numbers
.
dropLast
(
10
))
// Prints "[]"
n
: The number of elements to drop off the end of the
collection. n
must be greater than or equal to zero.
Returns: A subsequence that leaves off the specified number of elements
at the end.
Complexity: O(n), where n is the length of the collection.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
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 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.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, 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
() {
(
"\(
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.
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
{
(
names
[
i
])
}
// Prints "Sofia"
// Prints "Mateo"
Returns: A sequence of pairs enumerating the sequence.
Declaration
func
enumerated
() -
>
EnumeratedSequence
<
Slice
<
Base
>
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Returns the elements of self
that satisfy predicate
.
Note: The elements of the result are computed on-demand, as
the result is used. No buffering storage is allocated and each
traversal step invokes predicate
on one or more underlying
elements.
Declaration
func
filter
(
_
isIncluded
: @
escaping
(
Slice
<
Base
>
.
Elements
.
Element
) -
>
Bool
) -
>
LazyFilterCollection
<
Slice
<
Base
>
.
Elements
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
}) {
(
"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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Returns the first index in which an element of the collection satisfies the given predicate.
You can use the predicate to find an element of a type that doesn't
conform to the Equatable
protocol or to find an element that matches
particular criteria. Here's an example that finds a student name that
begins with the letter "A":
let
students
= [
"Kofi"
,
"Abena"
,
"Peter"
,
"Kweku"
,
"Akosua"
]
if
let
i
=
students
.
firstIndex
(
where
: { $
0
.
hasPrefix
(
"A"
) }) {
(
"\(
students
[
i
]
) starts with 'A'!"
)
}
// Prints "Abena starts with 'A'!"
predicate
: A closure that takes an element as its argument
and returns a Boolean value that indicates whether the passed element
represents a match.
Returns: The index of the first element for which predicate
returns
true
. If no elements in the collection satisfy the given predicate,
returns nil
.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
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.
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
: (
Slice
<
Base
>
.
Element
)
throws
-
>
ElementOfResult
?)
rethrows
-
>
[
ElementOfResult
]
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Returns the non-nil
results of mapping the given transformation over
this collection.
Use this method to receive a collection of nonoptional values when your transformation produces an optional value.
transform
: A closure that accepts an element of this
collection as its argument and returns an optional value.
Complexity: O(1)
Declaration
func
flatMap
<
ElementOfResult
>
(
_
transform
: @
escaping
(
Slice
<
Base
>
.
Elements
.
Element
) -
>
ElementOfResult
?) -
>
LazyMapCollection
<
LazyFilterCollection
<
LazyMapCollection
<
Slice
<
Base
>
.
Elements
,
ElementOfResult
?
>
>
,
ElementOfResult
>
Declared In
LazyCollectionProtocol
, LazySequenceProtocol
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.
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Returns the concatenated results of mapping the given transformation over this collection.
Use this method to receive a single-level collection when your
transformation produces a collection for each element.
Calling flatMap(_:)
on a collection c
is equivalent to calling
c.map(transform).joined()
.
Complexity: O(1)
Declaration
func
flatMap
<
SegmentOfResult
>
(
_
transform
: @
escaping
(
Slice
<
Base
>
.
Elements
.
Element
) -
>
SegmentOfResult
) -
>
LazyCollection
<
FlattenCollection
<
LazyMapCollection
<
Slice
<
Base
>
.
Elements
,
SegmentOfResult
>
>
>
where
SegmentOfResult
:
Collection
Declared In
LazyCollectionProtocol
, LazySequenceProtocol
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
{
(
word
)
}
// Prints "one"
// Prints "two"
// Prints "three"
numberWords
.
forEach
{
word
in
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Offsets the given index by the specified distance.
The value passed as n
must not offset i
beyond the bounds of the
collection.
Parameters:
i: A valid index of the collection.
n: The distance to offset i
. n
must not be negative unless the
collection conforms to the BidirectionalCollection
protocol.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Deprecated: all index distances are now of type Int.
Declaration
func
formIndex
<
T
>
(
_
i
:
inout
Slice
<
Base
>
.
Index
,
offsetBy
n
:
T
)
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Offsets the given index by the specified distance, or so that it equals the given limiting index.
The value passed as n
must not offset i
beyond the bounds of the
collection, unless the index passed as limit
prevents offsetting
beyond those bounds.
Parameters:
i: A valid index of the collection.
n: The distance to offset i
. n
must not be negative unless the
collection conforms to the BidirectionalCollection
protocol.
limit: A valid index of the collection to use as a limit. If n > 0
,
a limit that is less than i
has no effect. Likewise, if n < 0
, a
limit that is greater than i
has no effect.
Returns: true
if i
has been offset by exactly n
steps without
going beyond limit
; otherwise, false
. When the return value is
false
, the value of i
is equal to limit
.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Deprecated: all index distances are now of type Int.
Declaration
func
formIndex
<
T
>
(
_
i
:
inout
Slice
<
Base
>
.
Index
,
offsetBy
n
:
T
,
limitedBy
limit
:
Slice
<
Base
>
.
Index
) -
>
Bool
where
T
:
BinaryInteger
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Replaces the given index with its successor.
i
: A valid index of the collection. i
must be less than
endIndex
.
Declaration
func
formIndex
(
after
i
:
inout
Slice
<
Base
>
.
Index
)
Declared In
Slice
, LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Replaces the given index with its predecessor.
i
: A valid index of the collection. i
must be greater than
startIndex
.
Declaration
func
formIndex
(
before
i
:
inout
Slice
<
Base
>
.
Index
)
Declared In
Slice
, RandomAccessCollection
, BidirectionalCollection
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
)
(
s
[
i
])
// Prints "t"
The value passed as n
must not offset i
beyond the bounds of the
collection.
Parameters:
i: A valid index of the collection.
n: The distance to offset i
. n
must not be negative unless the
collection conforms to the BidirectionalCollection
protocol.
Returns: An index offset by n
from the index i
. If n
is positive,
this is the same value as the result of n
calls to index(after:)
.
If n
is negative, this is the same value as the result of -n
calls
to index(before:)
.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
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
)
(
s
[
i
])
// Prints "t"
The value passed as n
must not offset i
beyond the bounds of the
collection.
Parameters:
i: A valid index of the collection.
n: The distance to offset i
. n
must not be negative unless the
collection conforms to the BidirectionalCollection
protocol.
Returns: An index offset by n
from the index i
. If n
is positive,
this is the same value as the result of n
calls to index(after:)
.
If n
is negative, this is the same value as the result of -n
calls
to index(before:)
.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
Declared In
Slice
, RandomAccessCollection
, BidirectionalCollection
Deprecated: all index distances are now of type Int.
Declaration
func
index
<
T
>
(
_
i
:
Slice
<
Base
>
.
Index
,
offsetBy
n
:
T
) -
>
Slice
<
Base
>
.
Index
where
T
:
BinaryInteger
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
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
) {
(
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
)
(
j
)
// Prints "nil"
The value passed as n
must not offset i
beyond the bounds of the
collection, unless the index passed as limit
prevents offsetting
beyond those bounds.
Parameters:
i: A valid index of the collection.
n: The distance to offset i
. n
must not be negative unless the
collection conforms to the BidirectionalCollection
protocol.
limit: A valid index of the collection to use as a limit. If n > 0
,
a limit that is less than i
has no effect. Likewise, if n < 0
, a
limit that is greater than i
has no effect.
Returns: An index offset by n
from the index i
, unless that index
would be beyond limit
in the direction of movement. In that case,
the method returns nil
.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
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
) {
(
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
)
(
j
)
// Prints "nil"
The value passed as n
must not offset i
beyond the bounds of the
collection, unless the index passed as limit
prevents offsetting
beyond those bounds.
Parameters:
i: A valid index of the collection.
n: The distance to offset i
. n
must not be negative unless the
collection conforms to the BidirectionalCollection
protocol.
limit: A valid index of the collection to use as a limit. If n > 0
,
a limit that is less than i
has no effect. Likewise, if n < 0
, a
limit that is greater than i
has no effect.
Returns: An index offset by n
from the index i
, unless that index
would be beyond limit
in the direction of movement. In that case,
the method returns nil
.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
Declared In
Slice
, RandomAccessCollection
, BidirectionalCollection
Deprecated: all index distances are now of type Int.
Declaration
func
index
<
T
>
(
_
i
:
Slice
<
Base
>
.
Index
,
offsetBy
n
:
T
,
limitedBy
limit
:
Slice
<
Base
>
.
Index
) -
>
Slice
<
Base
>
.
Index
?
where
T
:
BinaryInteger
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
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.
i
: A valid index of the collection. i
must be less than
endIndex
.
Returns: The index value immediately after i
.
Declaration
Declaration
mutating
func
insert
(
_
newElement
:
Base
.
Element
,
at
i
:
Slice
<
Base
>
.
Index
)
Inserts a new element into the collection at the specified position.
The new element is inserted before the element currently at the
specified index. If you pass the collection's endIndex
property as
the index
parameter, the new element is appended to the
collection.
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
insert
(
100
,
at
:
3
)
numbers
.
insert
(
200
,
at
:
numbers
.
endIndex
)
(
numbers
)
// Prints "[1, 2, 3, 100, 4, 5, 200]"
Calling this method may invalidate any existing indices for use with this collection.
newElement
: The new element to insert into the collection.
i
: The position at which to insert the new element.
index
must be a valid index into the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
mutating
func
insert
(
_
newElement
:
Base
.
Element
,
at
i
:
Slice
<
Base
>
.
Index
)
Inserts a new element into the collection at the specified position.
The new element is inserted before the element currently at the
specified index. If you pass the collection's endIndex
property as
the index
parameter, the new element is appended to the
collection.
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
insert
(
100
,
at
:
3
)
numbers
.
insert
(
200
,
at
:
numbers
.
endIndex
)
(
numbers
)
// Prints "[1, 2, 3, 100, 4, 5, 200]"
Calling this method may invalidate any existing indices for use with this collection.
newElement
: The new element to insert into the collection.
i
: The position at which to insert the new element.
index
must be a valid index into the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
Declared In
RangeReplaceableCollection
Inserts the elements of a sequence into the collection at the specified position.
The new elements are inserted before the element currently at the
specified index. If you pass the collection's endIndex
property as the
index
parameter, the new elements are appended to the collection.
Here's an example of inserting a range of integers into an array of the same type:
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
insert
(
contentsOf
:
100
...
103
,
at
:
3
)
(
numbers
)
// Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"
Calling this method may invalidate any existing indices for use with this collection.
newElements
: The new elements to insert into the collection.
i
: The position at which to insert the new elements. index
must be a valid index of the collection.
Complexity: O(m), where m is the combined length of the collection
and newElements
. If i
is equal to the collection's endIndex
property, the complexity is O(n), where n is the length of
newElements
.
Declaration
mutating
func
insert
<
C
>
(
contentsOf
newElements
:
C
,
at
i
:
Slice
<
Base
>
.
Index
)
Declared In
RangeReplaceableCollection
Inserts the elements of a sequence into the collection at the specified position.
The new elements are inserted before the element currently at the
specified index. If you pass the collection's endIndex
property as the
index
parameter, the new elements are appended to the collection.
Here's an example of inserting a range of integers into an array of the same type:
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
insert
(
contentsOf
:
100
...
103
,
at
:
3
)
(
numbers
)
// Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"
Calling this method may invalidate any existing indices for use with this collection.
newElements
: The new elements to insert into the collection.
i
: The position at which to insert the new elements. index
must be a valid index of the collection.
Complexity: O(m), where m is the combined length of the collection
and newElements
. If i
is equal to the collection's endIndex
property, the complexity is O(n), where n is the length of
newElements
.
Declaration
mutating
func
insert
<
S
>
(
contentsOf
newElements
:
S
,
at
i
:
Slice
<
Base
>
.
Index
)
Declaration
mutating
func
insert
<
S
>
(
contentsOf
newElements
:
S
,
at
i
:
Slice
<
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
}) {
(
"The last negative number is \(
firstNegative
)."
)
}
// Prints "The last negative number is -6."
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 last element of the sequence that satisfies predicate
,
or nil
if there is no element that satisfies predicate
.
Declaration
Declared In
RandomAccessCollection
, BidirectionalCollection
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"
) }) {
(
"\(
students
[
i
]
) starts with 'A'!"
)
}
// Prints "Akosua starts with 'A'!"
predicate
: A closure that takes an element as its argument
and returns a Boolean value that indicates whether the passed element
represents a match.
Returns: The index of the last element in the collection that matches
predicate
, or nil
if no elements match.
Declaration
Declared In
RandomAccessCollection
, BidirectionalCollection
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.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Returns a LazyMapCollection
over this Collection
. The elements of
the result are computed lazily, each time they are read, by
calling transform
function on a base element.
Declaration
func
map
<
U
>
(
_
transform
: @
escaping
(
Slice
<
Base
>
.
Elements
.
Element
) -
>
U
) -
>
LazyMapCollection
<
Slice
<
Base
>
.
Elements
,
U
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, 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 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
}
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, 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 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
}
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Reorders the elements of the collection such that all the elements that match the given predicate are after all the elements that don't match.
After partitioning a collection, there is a pivot index p
where
no element before p
satisfies the belongsInSecondPartition
predicate and every element at or after p
satisfies
belongsInSecondPartition
.
In the following example, an array of numbers is partitioned by a predicate that matches elements greater than 30.
var
numbers
= [
30
,
40
,
20
,
30
,
30
,
60
,
10
]
let
p
=
numbers
.
partition
(
by
: { $
0
>
30
})
// p == 5
// numbers == [30, 10, 20, 30, 30, 60, 40]
The numbers
array is now arranged in two partitions. The first
partition, numbers[..<p]
, is made up of the elements that
are not greater than 30. The second partition, numbers[p...]
,
is made up of the elements that are greater than 30.
let
first
=
numbers
[..
<
p
]
// first == [30, 10, 20, 30, 30]
let
second
=
numbers
[
p
...]
// second == [60, 40]
belongsInSecondPartition
: A predicate used to partition
the collection. All elements satisfying this predicate are ordered
after all elements not satisfying it.
Returns: The index of the first element in the reordered collection
that matches belongsInSecondPartition
. If no elements in the
collection match belongsInSecondPartition
, the returned index is
equal to the collection's endIndex
.
Complexity: O(n)
Declaration
Declared In
MutableCollection
Removes and returns the last element of the collection.
Calling this method may invalidate all saved indices of this collection. Do not rely on a previously stored index value after altering a collection with any operation that can change its length.
Returns: The last element of the collection if the collection is not
empty; otherwise, nil
.
Complexity: O(1)
Declaration
mutating
func
popLast
() -
>
Slice
<
Base
>
.
Element
?
Declared In
RangeReplaceableCollection
Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.
If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
prefix
(
2
))
// Prints "[1, 2]"
(
numbers
.
prefix
(
10
))
// Prints "[1, 2, 3, 4, 5]"
maxLength
: The maximum number of elements to return.
maxLength
must be greater than or equal to zero.
Returns: A subsequence starting at the beginning of this collection
with at most maxLength
elements.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Returns a subsequence from the start of the collection through the specified position.
The resulting subsequence includes the element at the position end
.
The following example searches for the index of the number 40
in an
array of integers, and then prints the prefix of the array up to, and
including, that index:
let
numbers
= [
10
,
20
,
30
,
40
,
50
,
60
]
if
let
i
=
numbers
.
firstIndex
(
of
:
40
) {
(
numbers
.
prefix
(
through
:
i
))
}
// Prints "[10, 20, 30, 40]"
Using the prefix(through:)
method is equivalent to using a partial
closed range as the collection's subscript. The subscript notation is
preferred over prefix(through:)
.
if
let
i
=
numbers
.
firstIndex
(
of
:
40
) {
(
numbers
[...
i
])
}
// Prints "[10, 20, 30, 40]"
end
: The index of the last element to include in the
resulting subsequence. end
must be a valid index of the collection
that is not equal to the endIndex
property.
Returns: A subsequence up to, and including, the end
position.
Complexity: O(1)
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Returns a subsequence from the start of the collection up to, but not including, the specified position.
The resulting subsequence does not include the element at the position
end
. The following example searches for the index of the number 40
in an array of integers, and then prints the prefix of the array up to,
but not including, that index:
let
numbers
= [
10
,
20
,
30
,
40
,
50
,
60
]
if
let
i
=
numbers
.
firstIndex
(
of
:
40
) {
(
numbers
.
prefix
(
upTo
:
i
))
}
// Prints "[10, 20, 30]"
Passing the collection's starting index as the end
parameter results in
an empty subsequence.
(
numbers
.
prefix
(
upTo
:
numbers
.
startIndex
))
// Prints "[]"
Using the prefix(upTo:)
method is equivalent to using a partial
half-open range as the collection's subscript. The subscript notation is
preferred over prefix(upTo:)
.
if
let
i
=
numbers
.
firstIndex
(
of
:
40
) {
(
numbers
[..
<
i
])
}
// Prints "[10, 20, 30]"
end
: The "past the end" index of the resulting subsequence.
end
must be a valid index of the collection.
Returns: A subsequence up to, but not including, the end
position.
Complexity: O(1)
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Returns a lazy collection of the initial consecutive elements that
satisfy predicate
.
predicate
: A closure that takes an element of the collection
as its argument and returns true
if the element should be included
or false
otherwise. Once predicate
returns false
it will not be
called again.
Declaration
func
prefix
(
while
predicate
: @
escaping
(
Slice
<
Base
>
.
Element
) -
>
Bool
) -
>
LazyPrefixWhileCollection
<
Slice
<
Base
>
.
Elements
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
Returns a random element of the collection.
Call randomElement()
to select a random element from an array or
another collection. This example picks a name at random from an array:
let
names
= [
"Zoey"
,
"Chloe"
,
"Amani"
,
"Amaia"
]
let
randomName
=
names
.
randomElement
()!
// randomName == "Amani"
This method uses the default random generator, Random.default
. The call
to names.randomElement()
above is equivalent to calling
names.randomElement(using: &Random.default)
.
Returns: A random element from the collection. If the collection is
empty, the method returns nil
.
Declaration
func
randomElement
() -
>
Slice
<
Base
>
.
Element
?
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Returns a random element of the collection, using the given generator as a source for randomness.
Call randomElement(using:)
to select a random element from an array or
another collection when you are using a custom random number generator.
This example picks a name at random from an array:
let
names
= [
"Zoey"
,
"Chloe"
,
"Amani"
,
"Amaia"
]
let
randomName
=
names
.
randomElement
(
using
:
&
myGenerator
)!
// randomName == "Amani"
generator
: The random number generator to use when choosing
a random element.
Returns: A random element from the collection. If the collection is
empty, the method returns nil
.
Declaration
func
randomElement
<
T
>
(
using
generator
:
inout
T
) -
>
Slice
<
Base
>
.
Element
?
where
T
:
RandomNumberGenerator
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
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 case---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.
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
,
Slice
<
Base
>
.
Element
)
throws
-
>
Result
)
rethrows
-
>
Result
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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:
- The
updateAccumulatingResult
closure is called with the initial accumulating value---[:]
in this case---and 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:_:)
.
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
,
Slice
<
Base
>
.
Element
)
throws
-
>
())
rethrows
-
>
Result
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Declaration
mutating
func
remove
(
at
i
:
Slice
<
Base
>
.
Index
) -
>
Base
.
Element
Removes and returns the element at the specified position.
All the elements following the specified position are moved to close the gap. This example removes the middle element from an array of measurements.
var
measurements
= [
1.2
,
1.5
,
2.9
,
1.2
,
1.6
]
let
removed
=
measurements
.
remove
(
at
:
2
)
(
measurements
)
// Prints "[1.2, 1.5, 1.2, 1.6]"
Calling this method may invalidate any existing indices for use with this collection.
i
: The position of the element to remove. index
must be
a valid index of the collection that is not equal to the collection's
end index.
Returns: The removed element.
Complexity: O(n), where n is the length of the collection.
Declaration
mutating
func
remove
(
at
i
:
Slice
<
Base
>
.
Index
) -
>
Base
.
Element
Removes and returns the element at the specified position.
All the elements following the specified position are moved to close the gap. This example removes the middle element from an array of measurements.
var
measurements
= [
1.2
,
1.5
,
2.9
,
1.2
,
1.6
]
let
removed
=
measurements
.
remove
(
at
:
2
)
(
measurements
)
// Prints "[1.2, 1.5, 1.2, 1.6]"
Calling this method may invalidate any existing indices for use with this collection.
position
: The position of the element to remove. position
must be
a valid index of the collection that is not equal to the collection's
end index.
Returns: The removed element.
Complexity: O(n), where n is the length of the collection.
Declaration
Declared In
RangeReplaceableCollection
Removes all elements from the collection.
Calling this method may invalidate any existing indices for use with this collection.
keepCapacity
: Pass true
to request that the collection
avoid releasing its storage. Retaining the collection's storage can
be a useful optimization when you're planning to grow the collection
again. The default value is false
.
Complexity: O(n), where n is the length of the collection.
Declaration
mutating
func
removeAll
(
keepingCapacity
keepCapacity
:
Bool
=
default
)
Declared In
RangeReplaceableCollection
Removes all the elements that satisfy the given predicate.
Use this method to remove every element in a collection that meets particular criteria. This example removes all the odd values from an array of numbers:
var
numbers
= [
5
,
6
,
7
,
8
,
9
,
10
,
11
]
numbers
.
removeAll
(
where
: { $
0
%
2
==
1
})
// numbers == [6, 8, 10]
predicate
: A closure that takes an element of the
sequence as its argument and returns a Boolean value indicating
whether the element should be removed from the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
Declared In
RangeReplaceableCollection
Removes and returns the first element of the collection.
The collection must not be empty.
var
bugs
= [
"Aphid"
,
"Bumblebee"
,
"Cicada"
,
"Damselfly"
,
"Earwig"
]
bugs
.
removeFirst
()
(
bugs
)
// Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"
Calling this method may invalidate any existing indices for use with this collection.
Returns: The removed element.
Complexity: O(n), where n is the length of the collection.
Declaration
mutating
func
removeFirst
() -
>
Slice
<
Base
>
.
Element
Declared In
RangeReplaceableCollection
Removes the specified number of elements from the beginning of the collection.
var
bugs
= [
"Aphid"
,
"Bumblebee"
,
"Cicada"
,
"Damselfly"
,
"Earwig"
]
bugs
.
removeFirst
(
3
)
(
bugs
)
// Prints "["Damselfly", "Earwig"]"
Calling this method may invalidate any existing indices for use with this collection.
n
: The number of elements to remove from the collection.
n
must be greater than or equal to zero and must not exceed the
number of elements in the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
mutating
func
removeFirst
(
_
n
:
Int
)
Declared In
RangeReplaceableCollection
Removes and returns the last element of the collection.
The collection must not be empty.
Calling this method may invalidate all saved indices of this collection. Do not rely on a previously stored index value after altering a collection with any operation that can change its length.
Returns: The last element of the collection.
Complexity: O(1)
Declaration
mutating
func
removeLast
() -
>
Slice
<
Base
>
.
Element
Declared In
RangeReplaceableCollection
Removes the specified number of elements from the end of the collection.
Attempting to remove more elements than exist in the collection triggers a runtime error.
Calling this method may invalidate all saved indices of this collection. Do not rely on a previously stored index value after altering a collection with any operation that can change its length.
n
: The number of elements to remove from the collection.
n
must be greater than or equal to zero and must not exceed the
number of elements in the collection.
Complexity: O(n), where n is the specified number of elements.
Declaration
mutating
func
removeLast
(
_
n
:
Int
)
Declared In
RangeReplaceableCollection
Removes the specified subrange of elements from the collection.
var
bugs
= [
"Aphid"
,
"Bumblebee"
,
"Cicada"
,
"Damselfly"
,
"Earwig"
]
bugs
.
removeSubrange
(
1
...
3
)
(
bugs
)
// Prints "["Aphid", "Earwig"]"
Calling this method may invalidate any existing indices for use with this collection.
bounds
: The subrange of the collection to remove. The bounds
of the range must be valid indices of the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
Declared In
Slice
, RangeReplaceableCollection
Removes the elements in the specified subrange from the collection.
All the elements following the specified position are moved to close the gap. This example removes three elements from the middle of an array of measurements.
var
measurements
= [
1.2
,
1.5
,
2.9
,
1.2
,
1.5
]
measurements
.
removeSubrange
(
1
..
<
4
)
(
measurements
)
// Prints "[1.2, 1.5]"
Calling this method may invalidate any existing indices for use with this collection.
bounds
: The range of the collection to be removed. The
bounds of the range must be valid indices of the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
mutating
func
removeSubrange
<
R
>
(
_
bounds
:
R
)
Declared In
RangeReplaceableCollection
Replaces the specified subrange of elements with the given collection.
This method has the effect of removing the specified range of elements from the collection and inserting the new elements at the same location. The number of new elements need not match the number of elements being removed.
In this example, three elements in the middle of an array of integers are
replaced by the five elements of a Repeated<Int>
instance.
var
nums
= [
10
,
20
,
30
,
40
,
50
]
nums
.
replaceSubrange
(
1
...
3
,
with
:
repeatElement
(
1
,
count
:
5
))
(
nums
)
// Prints "[10, 1, 1, 1, 1, 1, 50]"
If you pass a zero-length range as the subrange
parameter, this method
inserts the elements of newElements
at subrange.startIndex
. Calling
the insert(contentsOf:at:)
method instead is preferred.
Likewise, if you pass a zero-length collection as the newElements
parameter, this method removes the elements in the given subrange
without replacement. Calling the removeSubrange(_:)
method instead is
preferred.
Calling this method may invalidate any existing indices for use with this collection.
Parameters: subrange: The subrange of the collection to replace. The bounds of the range must be valid indices of the collection. newElements: The new elements to add to the collection.
Complexity: O(m), where m is the combined length of the collection
and newElements
. If the call to replaceSubrange
simply appends the
contents of newElements
to the collection, the complexity is O(n),
where n is the length of newElements
.
Declaration
Replaces the specified subrange of elements with the given collection.
This method has the effect of removing the specified range of elements from the collection and inserting the new elements at the same location. The number of new elements need not match the number of elements being removed.
In this example, three elements in the middle of an array of integers are
replaced by the five elements of a Repeated<Int>
instance.
var
nums
= [
10
,
20
,
30
,
40
,
50
]
nums
.
replaceSubrange
(
1
...
3
,
with
:
repeatElement
(
1
,
count
:
5
))
(
nums
)
// Prints "[10, 1, 1, 1, 1, 1, 50]"
If you pass a zero-length range as the subrange
parameter, this method
inserts the elements of newElements
at subrange.startIndex
. Calling
the insert(contentsOf:at:)
method instead is preferred.
Likewise, if you pass a zero-length collection as the newElements
parameter, this method removes the elements in the given subrange
without replacement. Calling the removeSubrange(_:)
method instead is
preferred.
Calling this method may invalidate any existing indices for use with this collection.
Parameters: subrange: The subrange of the collection to replace. The bounds of the range must be valid indices of the collection. newElements: The new elements to add to the collection.
Complexity: O(m), where m is the combined length of the collection
and newElements
. If the call to replaceSubrange
simply appends the
contents of newElements
to the collection, the complexity is O(n),
where n is the length of newElements
.
Declaration
mutating
func
replaceSubrange
<
C
,
R
>
(
_
subrange
:
R
,
with
newElements
:
C
)
Declared In
RangeReplaceableCollection
Prepares the collection to store the specified number of elements, when doing so is appropriate for the underlying type.
If you will be adding a known number of elements to a collection, use
this method to avoid multiple reallocations. A type that conforms to
RangeReplaceableCollection
can choose how to respond when this method
is called. Depending on the type, it may make sense to allocate more or
less storage than requested or to take no action at all.
n
: The requested number of elements to store.
Declaration
mutating
func
reserveCapacity
(
_
n
:
Int
)
Declared In
RangeReplaceableCollection
Reverses the elements of the collection in place.
The following example reverses the elements of an array of characters:
var
characters
: [
Character
] = [
"C"
,
"a"
,
"f"
,
"é"
]
characters
.
reverse
()
(
characters
)
// Prints "["é", "f", "a", "C"]
Complexity: O(n), where n is the number of elements in the collection.
Declaration
mutating
func
reverse
()
Declared In
MutableCollection
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
() -
>
[
Slice
<
Base
>
.
Element
]
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Shuffles the collection in place.
Use the shuffle()
method to randomly reorder the elements of an
array.
var
names
= [
"Alejandro"
,
"Camila"
,
"Diego"
,
"Luciana"
,
"Luis"
,
"Sofía"
]
names
.
shuffle
(
using
:
myGenerator
)
// names == ["Luis", "Camila", "Luciana", "Sofía", "Alejandro", "Diego"]
This method uses the default random generator, Random.default
. The call
to names.shuffle()
above is equivalent to calling
names.shuffle(using: &Random.default)
.
Complexity: O(n)
Declaration
mutating
func
shuffle
()
Declared In
MutableCollection
Shuffles the collection in place, using the given generator as a source for randomness.
You use this method to randomize the elements of a collection when you
are using a custom random number generator. For example, you can use the
shuffle(using:)
method to randomly reorder the elements of an array.
var
names
= [
"Alejandro"
,
"Camila"
,
"Diego"
,
"Luciana"
,
"Luis"
,
"Sofía"
]
names
.
shuffle
(
using
:
&
myGenerator
)
// names == ["Sofía", "Alejandro", "Camila", "Luis", "Diego", "Luciana"]
generator
: The random number generator to use when shuffling
the collection.
Complexity: O(n)
Declaration
mutating
func
shuffle
<
T
>
(
using
generator
:
inout
T
)
Declared In
MutableCollection
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
() -
>
[
Slice
<
Base
>
.
Element
]
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
) -
>
[
Slice
<
Base
>
.
Element
]
where
T
:
RandomNumberGenerator
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Sorts the collection in place, using the given predicate as the comparison between elements.
When you want to sort a collection of elements that doesn't conform to
the Comparable
protocol, pass a closure to this method that returns
true
when the first element passed should be ordered before the
second.
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 closure provides an ordering for an array of a custom enumeration that describes an HTTP response. The predicate orders errors before successes and sorts the error responses by their error code.
enum
HTTPResponse
{
case
ok
case
error
(
Int
)
}
var
responses
: [
HTTPResponse
] = [.
error
(
500
), .
ok
, .
ok
, .
error
(
404
), .
error
(
403
)]
responses
.
sort
{
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
}
}
(
responses
)
// Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
Alternatively, use this method to sort a collection of elements that do
conform to Comparable
when you want the sort to be descending instead
of ascending. Pass the greater-than operator (>
) operator as the
predicate.
var
students
= [
"Kofi"
,
"Abena"
,
"Peter"
,
"Kweku"
,
"Akosua"
]
students
.
sort
(
by
:
>
)
(
students
)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
areInIncreasingOrder
: A predicate that returns true
if its
first argument should be ordered before its second argument;
otherwise, false
. If areInIncreasingOrder
throws an error during
the sort, the elements may be in a different order, but none will be
lost.
Declaration
Declared In
MutableCollection
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
}
}
(
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
:
>
)
(
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.
(
students
.
sorted
())
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Returns the longest possible subsequences of the collection, in order, that don't contain elements satisfying the given predicate.
The resulting array consists of at most maxSplits + 1
subsequences.
Elements that are used to split the sequence are not returned as part of
any subsequence.
The following examples show the effects of the maxSplits
and
omittingEmptySubsequences
parameters when splitting a string using a
closure that matches spaces. The first use of split
returns each word
that was originally separated by one or more spaces.
let
line
=
"BLANCHE: I don't want realism. I want magic!"
(
line
.
split
(
whereSeparator
: { $
0
==
" "
}))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
The second example passes 1
for the maxSplits
parameter, so the
original string is split just once, into two new strings.
(
line
.
split
(
maxSplits
:
1
,
whereSeparator
: { $
0
==
" "
}))
// Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
The final example passes false
for the omittingEmptySubsequences
parameter, so the returned array contains empty strings where spaces
were repeated.
(
line
.
split
(
omittingEmptySubsequences
:
false
,
whereSeparator
: { $
0
==
" "
}))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
Parameters:
maxSplits: The maximum number of times to split the collection, 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 collection 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 collection satisfying the isSeparator
predicate. The default value is true
.
isSeparator: A closure that takes an element as an argument and
returns a Boolean value indicating whether the collection should be
split at that element.
Returns: An array of subsequences, split from this collection's
elements.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
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
.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, 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 all the elements in the collection.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
suffix
(
2
))
// Prints "[4, 5]"
(
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.
Returns: A subsequence terminating at the end of the collection with at
most maxLength
elements.
Complexity: O(n), where n is the length of the collection.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Returns a subsequence from the specified position to the end of the collection.
The following example searches for the index of the number 40
in an
array of integers, and then prints the suffix of the array starting at
that index:
let
numbers
= [
10
,
20
,
30
,
40
,
50
,
60
]
if
let
i
=
numbers
.
firstIndex
(
of
:
40
) {
(
numbers
.
suffix
(
from
:
i
))
}
// Prints "[40, 50, 60]"
Passing the collection's endIndex
as the start
parameter results in
an empty subsequence.
(
numbers
.
suffix
(
from
:
numbers
.
endIndex
))
// Prints "[]"
Using the suffix(from:)
method is equivalent to using a partial range
from the index as the collection's subscript. The subscript notation is
preferred over suffix(from:)
.
if
let
i
=
numbers
.
firstIndex
(
of
:
40
) {
(
numbers
[
i
...])
}
// Prints "[40, 50, 60]"
start
: The index at which to start the resulting subsequence.
start
must be a valid index of the collection.
Returns: A subsequence starting at the start
position.
Complexity: O(1)
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Exchanges the values at the specified indices of the collection.
Both parameters must be valid indices of the collection that are not
equal to endIndex
. Calling swapAt(_:_:)
with the same index as both
i
and j
has no effect.
Parameters: i: The index of the first value to swap. j: The index of the second value to swap.
Declaration
Declared In
MutableCollection
72 inherited items hidden. (Show all)
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 : Collection
A concatenation of the elements of self
.
Declaration
func
joined
() -
>
LazyCollection
<
FlattenCollection
<
Slice
<
Base
>
.
Elements
>
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
1 inherited item hidden. (Show all)
Where Element : Comparable
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
]
(
a
.
lexicographicallyPrecedes
(
b
))
// Prints "true"
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
()
(
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
() -
>
Slice
<
Base
>
.
Element
?
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
()
(
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
() -
>
Slice
<
Base
>
.
Element
?
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Sorts the collection in place.
You can sort any mutable collection 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 (<
).
var
students
= [
"Kofi"
,
"Abena"
,
"Peter"
,
"Kweku"
,
"Akosua"
]
students
.
sort
()
(
students
)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
To sort the elements of your collection in descending order, pass the
greater-than operator (>
) to the sort(by:)
method.
students
.
sort
(
by
:
>
)
(
students
)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
Declaration
mutating
func
sort
()
Declared In
MutableCollection
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
()
(
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
:
>
)
(
descendingStudents
)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
Returns: A sorted array of the sequence's elements.
Declaration
func
sorted
() -
>
[
Slice
<
Base
>
.
Element
]
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
5 inherited items hidden. (Show all)
Where Element : Equatable
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"
]
(
cast
.
contains
(
"Marlon"
))
// Prints "true"
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
(
a
.
elementsEqual
(
b
))
// Prints "false"
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
Returns the first index where the specified value appears in the collection.
After using firstIndex(of:)
to find the position of a particular element
in a collection, you can use it to access the element by subscripting.
This example shows how you can modify one of the names in an array of
students.
var
students
= [
"Ben"
,
"Ivy"
,
"Jordell"
,
"Maxime"
]
if
let
i
=
students
.
firstIndex
(
of
:
"Maxime"
) {
students
[
i
] =
"Max"
}
(
students
)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"
element
: An element to search for in the collection.
Returns: The first index where element
is found. If element
is not
found in the collection, returns nil
.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
Returns the last index where the specified value appears in the collection.
After using lastIndex(of:)
to find the position of the last instance of
a particular element in a collection, you can use it to access the
element by subscripting. This example shows how you can modify one of
the names in an array of students.
var
students
= [
"Ben"
,
"Ivy"
,
"Jordell"
,
"Ben"
,
"Maxime"
]
if
let
i
=
students
.
lastIndex
(
of
:
"Ben"
) {
students
[
i
] =
"Benjamin"
}
(
students
)
// Prints "["Ben", "Ivy", "Jordell", "Benjamin", "Max"]"
element
: An element to search for in the collection.
Returns: The last index where element
is found. If element
is not
found in the collection, returns nil
.
Declaration
Declared In
RandomAccessCollection
, BidirectionalCollection
Returns the longest possible subsequences of the collection, 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 collection 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!"
(
line
.
split
(
separator
:
" "
))
// 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.
(
line
.
split
(
separator
:
" "
,
maxSplits
:
1
))
// 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.
(
line
.
split
(
separator
:
" "
,
omittingEmptySubsequences
:
false
))
// 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 collection, 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 collection 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 collection and for each instance of separator
at
the start or end of the collection. If true
, only nonempty
subsequences are returned. The default value is true
.
Returns: An array of subsequences, split from this collection's
elements.
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
(
b
.
starts
(
with
:
a
))
// Prints "true"
Passing a sequence with no elements or an empty collection as
possiblePrefix
always results in true
.
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
6 inherited items hidden. (Show all)
Where Element : Sequence
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
{
(
range
)
}
// Prints "0..<3"
// Prints "8..<10"
// Prints "15..<17"
// Use 'joined()' to access each element of each range:
for
index
in
ranges
.
joined
() {
(
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
<
Slice
<
Base
>
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
])
(
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
<
Slice
<
Base
>
>
where
Separator
:
Sequence
,
Separator
.
Element
==
Slice
<
Base
>
.
Element
.
Element
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
2 inherited items hidden. (Show all)
Where Element : StringProtocol
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
:
", "
)
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
1 inherited item hidden. (Show all)
Where Elements : BidirectionalCollection
Returns the elements of the collection in reverse order.
Complexity: O(1)
Declaration
func
reversed
() -
>
LazyCollection
<
ReversedCollection
<
Slice
<
Base
>
.
Elements
>
>
Declared In
LazyCollectionProtocol
1 inherited item hidden. (Show all)
Where Elements : LazyCollectionProtocol
1 inherited item hidden. (Show all)
Where Elements : LazySequenceProtocol
Declaration
var
lazy
:
Slice
<
Base
>
.
Elements
{
get
}
Declared In
LazyCollectionProtocol
, LazySequenceProtocol
1 inherited item hidden. (Show all)
Where Index : Strideable, Indices == Range, Index.Stride == Int
The indices that are valid for subscripting the collection, in ascending order.
Declaration
Declared In
RandomAccessCollection
Returns the distance between two indices.
Parameters:
start: A valid index of the collection.
end: Another valid index of the collection. If end
is equal to
start
, the result is zero.
Returns: The distance between start
and end
.
Complexity: O(1)
Declaration
Declared In
RandomAccessCollection
Returns an index that is the specified distance from the given index.
The following example obtains an index advanced four positions from an array's starting index and then prints the element at that position.
let
numbers
= [
10
,
20
,
30
,
40
,
50
]
let
i
=
numbers
.
index
(
numbers
.
startIndex
,
offsetBy
:
4
)
(
numbers
[
i
])
// Prints "50"
The value passed as n
must not offset i
beyond the bounds of the
collection.
Parameters:
i: A valid index of the collection.
n: The distance to offset i
.
Returns: An index offset by n
from the index i
. If n
is positive,
this is the same value as the result of n
calls to index(after:)
.
If n
is negative, this is the same value as the result of -n
calls
to index(before:)
.
Complexity: O(1)
Declaration
Declared In
RandomAccessCollection
Returns the position immediately after the given index.
i
: A valid index of the collection. i
must be less than
endIndex
.
Returns: The index value immediately after i
.
Declaration
Declared In
RandomAccessCollection
Returns the position immediately after the given index.
i
: A valid index of the collection. i
must be greater than
startIndex
.
Returns: The index value immediately before i
.
Declaration
Declared In
RandomAccessCollection
5 inherited items hidden. (Show all)
Where Indices == DefaultIndices
The indices that are valid for subscripting the collection, in ascending order.
A collection's indices
property can hold a strong reference to the
collection itself, causing the collection to be non-uniquely referenced.
If you mutate the collection while iterating over its indices, a strong
reference can cause an unexpected copy of the collection. To avoid the
unexpected copy, use the index(after:)
method starting with
startIndex
to produce indices instead.
var
c
=
MyFancyCollection
([
10
,
20
,
30
,
40
,
50
])
var
i
=
c
.
startIndex
while
i
!=
c
.
endIndex
{
c
[
i
] /=
5
i
=
c
.
index
(
after
:
i
)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])
Declaration
var
indices
:
DefaultIndices
<
Slice
<
Base
>
>
{
get
}
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
1 inherited item hidden. (Show all)
Where Iterator == IndexingIterator
Returns an iterator over the elements of the collection.
Declaration
func
makeIterator
() -
>
IndexingIterator
<
Slice
<
Base
>
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
1 inherited item hidden. (Show all)
Where SubSequence == AnySequence
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
: (
Slice
<
Base
>
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
AnySequence
<
Slice
<
Base
>
.
Element
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, 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
]
(
numbers
.
dropFirst
(
2
))
// Prints "[3, 4, 5]"
(
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
<
Slice
<
Base
>
.
Element
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, 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
]
(
numbers
.
dropLast
(
2
))
// Prints "[1, 2, 3]"
(
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
<
Slice
<
Base
>
.
Element
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
]
(
numbers
.
prefix
(
2
))
// Prints "[1, 2]"
(
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
<
Slice
<
Base
>
.
Element
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
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
: (
Slice
<
Base
>
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
AnySequence
<
Slice
<
Base
>
.
Element
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, 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!"
(
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.
(
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.
(
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
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, 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
]
(
numbers
.
suffix
(
2
))
// Prints "[4, 5]"
(
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
<
Slice
<
Base
>
.
Element
>
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, LazySequenceProtocol
, BidirectionalCollection
, Sequence
7 inherited items hidden. (Show all)
Where SubSequence == Slice
Accesses a contiguous subrange of the collection's elements.
The accessed slice uses the same indices for the same elements as the
original collection. Always use the slice's startIndex
property
instead of assuming that its indices start at a particular value.
This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array.
let
streets
= [
"Adams"
,
"Bryant"
,
"Channing"
,
"Douglas"
,
"Evarts"
]
let
streetsSlice
=
streets
[
2
..
<
streets
.
endIndex
]
(
streetsSlice
)
// Prints "["Channing", "Douglas", "Evarts"]"
let
index
=
streetsSlice
.
firstIndex
(
of
:
"Evarts"
)
// 4
(
streets
[
index
!])
// Prints "Evarts"
bounds
: A range of the collection's indices. The bounds of
the range must be valid indices of the collection.
Complexity: O(1)
Declaration
Declared In
LazyCollectionProtocol
, MutableCollection
, RandomAccessCollection
, RangeReplaceableCollection
, Collection
, BidirectionalCollection
1 inherited item hidden. (Show all)
A view into a subsequence of elements of another collection.
A slice stores a base collection and the start and end indices of the view. It does not copy the elements from the collection into separate storage. Thus, creating a slice has O(1) complexity.
Slices Share Indices
Indices of a slice can be used interchangeably with indices of the base collection. An element of a slice is located under the same index in the slice and in the base collection, as long as neither the collection nor the slice has been mutated since the slice was created.
For example, suppose you have an array holding the number of absences from each class during a session.
You're tasked with finding the day with the most absences in the second half of the session. To find the index of the day in question, follow these setps:
1) Create a slice of the
absences
array that holds the second half of the days. 2) Use themax(by:)
method to determine the index of the day with the most absences. 3) Print the result using the index found in step 2 on the originalabsences
array.Here's an implementation of those steps:
Slices Inherit Semantics
A slice inherits the value or reference semantics of its base collection. That is, if a
Slice
instance is wrapped around a mutable collection that has value semantics, such as an array, mutating the original collection would trigger a copy of that collection, and not affect the base collection stored inside of the slice.For example, if you update the last element of the
absences
array from0
to2
, thesecondHalf
slice is unchanged.Use slices only for transient computation. A slice may hold a reference to the entire storage of a larger collection, not just to the portion it presents, even after the base collection's lifetime ends. Long-term storage of a slice may therefore prolong the lifetime of elements that are no longer otherwise accessible, which can erroneously appear to be memory leakage.
Note: Using a
Slice
instance with a mutable collection requires that the base collection'ssubscript(_: Index)
setter does not invalidate indices. If mutations need to invalidate indices in your custom collection type, don't useSlice
as its subsequence type. Instead, define your own subsequence type that takes your index invalidation requirements into account.