struct
DefaultIndices
A collection of indices for an arbitrary collection
Inheritance | Collection |
---|---|
Associated Types |
This associated type appears as a requirement in the
By default, a collection conforms to the |
Instance Variables
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
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
:
DefaultIndices
<
Elements
>
.
Index
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
:
Self
.
Element
?
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
<
Elements
>
.
Indices
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
The position of the first element in a nonempty collection.
If the collection is empty, startIndex
is equal to endIndex
.
Declaration
var
startIndex
:
DefaultIndices
<
Elements
>
.
Index
A value less than or equal to the number of elements in the collection.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the length of the collection.
Declaration
var
underestimatedCount
:
Int
Subscripts
Accesses a contiguous subrange of the collection's elements.
The accessed slice uses the same indices for the same elements as the
original collection uses. 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"
- Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.
Complexity: O(1)
Declaration
@
inlinable
public
subscript
(
bounds
:
Range
<
DefaultIndices
<
Elements
>
.
Index
>
) -
>
DefaultIndices
<
Elements
>
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.
- Parameter position: The position of the element to access.
position
must be a valid index of the collection that is not equal to theendIndex
property.
Complexity: O(1)
Declaration
@
inlinable
public
subscript
(
i
:
DefaultIndices
<
Elements
>
.
Index
) -
>
Elements
.
Index
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
- Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.
Complexity: O(1)
Declaration
@
inlinable
public
subscript
<
R
>
(
r
:
R
)
where
R
:
RangeExpression
,
Self
.
Index
==
R
.
Bound
-
>
Self
.
SubSequence
Declaration
@
inlinable
public
subscript
(
x
: (
UnboundedRange_
) -
>
()) -
>
Self
.
SubSequence
Instance Methods
Returns the distance between two indices.
Unless the collection conforms to the BidirectionalCollection
protocol,
start
must be less than or equal to end
.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is the resulting distance.
Declaration
@
inlinable
public
func
distance
(
from
start
:
Self
.
Index
,
to
end
:
Self
.
Index
) -
>
Int
Returns a subsequence by skipping elements while predicate
returns
true
and returning the remaining elements.
- Parameter predicate: A closure that takes an element of the
sequence as its argument and returns
true
if the element should be skipped orfalse
if it should be included. Once the predicate returnsfalse
it will not be called again.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
func
drop
(
while
predicate
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
.
SubSequence
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 "[]"
- Parameter k: The number of elements to drop from the beginning of
the collection.
k
must be greater than or equal to zero.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is the number of elements to drop from the beginning of the collection.
Declaration
@
inlinable
public
func
dropFirst
(
_
k
:
Int
=
1
) -
>
Self
.
SubSequence
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 "[]"
- Parameter k: The number of elements to drop off the end of the
collection.
k
must be greater than or equal to zero.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the length of the collection.
Declaration
@
inlinable
public
func
dropLast
(
_
k
:
Int
=
1
) -
>
Self
.
SubSequence
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'!"
- Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
func
firstIndex
(
where
predicate
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
.
Index
?
Offsets the given index by the specified distance.
The value passed as distance
must not offset i
beyond the bounds of
the collection.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is the absolute value ofdistance
.
Declaration
@
inlinable
public
func
formIndex
(
_
i
:
inout
Self
.
Index
,
offsetBy
distance
:
Int
)
Offsets the given index by the specified distance, or so that it equals the given limiting index.
The value passed as distance
must not offset i
beyond the bounds of
the collection, unless the index passed as limit
prevents offsetting
beyond those bounds.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is the absolute value ofdistance
.
Declaration
Replaces the given index with its successor.
- Parameter i: A valid index of the collection.
i
must be less thanendIndex
.
Declaration
@
inlinable
public
func
formIndex
(
after
i
:
inout
DefaultIndices
<
Elements
>
.
Index
)
Replaces the given index with its successor.
- Parameter i: A valid index of the collection.
i
must be less thanendIndex
.
Declaration
@
inlinable
public
func
formIndex
(
after
i
:
inout
Self
.
Index
)
Returns an index that is the specified distance from the given index.
The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position.
let
s
=
"Swift"
let
i
=
s
.
index
(
s
.
startIndex
,
offsetBy
:
4
)
(
s
[
i
])
// Prints "t"
The value passed as distance
must not offset i
beyond the bounds of
the collection.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is the absolute value ofdistance
.
Declaration
@
inlinable
public
func
index
(
_
i
:
Self
.
Index
,
offsetBy
distance
:
Int
) -
>
Self
.
Index
Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.
The following example obtains an index advanced four positions from a
string's starting index and then prints the character at that position.
The operation doesn't require going beyond the limiting s.endIndex
value, so it succeeds.
let
s
=
"Swift"
if
let
i
=
s
.
index
(
s
.
startIndex
,
offsetBy
:
4
,
limitedBy
:
s
.
endIndex
) {
(
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 distance
must not offset i
beyond the bounds of
the collection, unless the index passed as limit
prevents offsetting
beyond those bounds.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is the absolute value ofdistance
.
Declaration
@
inlinable
public
func
index
(
_
i
:
Self
.
Index
,
offsetBy
distance
:
Int
,
limitedBy
limit
:
Self
.
Index
) -
>
Self
.
Index
?
Returns the position immediately after the given index.
The successor of an index must be well defined. For an index i
into a
collection c
, calling c.index(after: i)
returns the same index every
time.
- Parameter i: A valid index of the collection.
i
must be less thanendIndex
.
Declaration
@
inlinable
public
func
index
(
after
i
:
DefaultIndices
<
Elements
>
.
Index
) -
>
DefaultIndices
<
Elements
>
.
Index
Returns an array containing the results of mapping the given closure over the sequence's elements.
In this example, map
is used first to convert the names in the array
to lowercase strings and then to count their characters.
let
cast
= [
"Vivien"
,
"Marlon"
,
"Kim"
,
"Karl"
]
let
lowercaseNames
=
cast
.
map
{ $
0
.
lowercased
() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let
letterCounts
=
cast
.
map
{ $
0
.
count
}
// 'letterCounts' == [6, 6, 3, 4]
- Parameter transform: A mapping closure.
transform
accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type.
Declaration
@
inlinable
public
func
map
<
T
>
(
_
transform
: (
Self
.
Element
)
throws
-
>
T
)
rethrows
-
>
[
T
]
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]"
- Parameter maxLength: The maximum number of elements to return.
maxLength
must be greater than or equal to zero.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is the number of elements to select from the beginning of the collection.
Declaration
@
inlinable
public
func
prefix
(
_
maxLength
:
Int
) -
>
Self
.
SubSequence
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]"
- Parameter end: The index of the last element to include in the
resulting subsequence.
end
must be a valid index of the collection that is not equal to theendIndex
property.
Complexity: O(1)
Declaration
@
inlinable
public
func
prefix
(
through
position
:
Self
.
Index
) -
>
Self
.
SubSequence
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]"
- Parameter end: The "past the end" index of the resulting subsequence.
end
must be a valid index of the collection.
Complexity: O(1)
Declaration
@
inlinable
public
func
prefix
(
upTo
end
:
Self
.
Index
) -
>
Self
.
SubSequence
Returns a subsequence containing the initial elements until predicate
returns false
and skipping the remaining elements.
- Parameter predicate: A closure that takes an element of the
sequence as its argument and returns
true
if the element should be included orfalse
if it should be excluded. Once the predicate returnsfalse
it will not be called again.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
func
prefix
(
while
predicate
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
.
SubSequence
Returns a random element of the collection.
Call randomElement()
to select a random element from an array or
another collection. This example picks a name at random from an array:
let
names
= [
"Zoey"
,
"Chloe"
,
"Amani"
,
"Amaia"
]
let
randomName
=
names
.
randomElement
()!
// randomName == "Amani"
This method is equivalent to calling randomElement(using:)
, passing in
the system's default random generator.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the length of the collection.
Declaration
@
inlinable
public
func
randomElement
() -
>
Self
.
Element
?
Returns a random element of the collection, using the given generator as a source for randomness.
Call randomElement(using:)
to select a random element from an array or
another collection when you are using a custom random number generator.
This example picks a name at random from an array:
let
names
= [
"Zoey"
,
"Chloe"
,
"Amani"
,
"Amaia"
]
let
randomName
=
names
.
randomElement
(
using
:
&
myGenerator
)!
// randomName == "Amani"
- Parameter generator: The random number generator to use when choosing a random element.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the length of the collection.
Note: The algorithm used to select a random element may change in a future version of Swift. If you're passing a generator that results in the same sequence of elements each time you run your program, that sequence may change when your program is compiled using a different version of Swift.
Declaration
@
inlinable
public
func
randomElement
<
T
>
(
using
generator
:
inout
T
) -
>
Self
.
Element
?
where
T
:
RandomNumberGenerator
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!"]"
Complexity: O(n), where n is the length of the collection.
Declaration
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]"
- Parameter maxLength: The maximum number of elements to return. The
value of
maxLength
must be greater than or equal to zero.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the length of the collection.
Declaration
@
inlinable
public
func
suffix
(
_
maxLength
:
Int
) -
>
Self
.
SubSequence
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]"
- Parameter start: The index at which to start the resulting subsequence.
start
must be a valid index of the collection.
Complexity: O(1)
Declaration
@
inlinable
public
func
suffix
(
from
start
:
Self
.
Index
) -
>
Self
.
SubSequence
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.