struct
CountableRange
<
Bound
where
Bound
:
Comparable
,
Bound
:
_Strideable
,
Bound
.
Stride
:
SignedInteger
>
Inheritance |
BidirectionalCollection, Collection, CustomDebugStringConvertible, CustomReflectable, CustomStringConvertible, Equatable, RandomAccessCollection, Sequence
View Protocol Hierarchy →
|
---|---|
Associated Types |
The bound type of the range.
A type that represents a position in the range.
A type that represents the number of steps between two indices, where one value is reachable from the other. In Swift, reachability refers to the ability to produce one value from
the other through zero or more applications of
A sequence that represents a contiguous subrange of the collection's elements.
A type that represents the indices that are valid for subscripting the collection, in ascending order. |
Import |
|
Initializers
Creates an instance equivalent to the given range.
An equivalent range must be representable as an instance of CountableRange
.
For example, passing a closed range with an upper bound of Int.max
triggers a runtime error, because the resulting half-open range would
require an upper bound of Int.max + 1
, which is not representable as
an Int
.
other
: A range to convert to a CountableRange
instance.
Declaration
init
(
_
other
:
ClosedRange
<
Bound
>
)
Creates an instance equivalent to the given range.
An equivalent range must be representable as an instance of CountableRange
.
For example, passing a closed range with an upper bound of Int.max
triggers a runtime error, because the resulting half-open range would
require an upper bound of Int.max + 1
, which is not representable as
an Int
.
other
: A range to convert to a CountableRange
instance.
Declaration
init
(
_
other
:
CountableClosedRange
<
Bound
>
)
Creates an instance equivalent to the given range.
other
: A range to convert to a CountableRange
instance.
Declaration
init
(
_
other
:
CountableRange
<
Bound
>
)
Creates an instance equivalent to the given range.
other
: A range to convert to a CountableRange
instance.
Declaration
init
(
_
other
:
Range
<
Bound
>
)
Creates an instance with the given bounds.
Because this initializer does not perform any checks, it should be used
as an optimization only when you are absolutely certain that lower
is
less than or equal to upper
. Using the half-open range operator
(..<
) to form CountableRange
instances is preferred.
bounds
: A tuple of the lower and upper bounds of the range.
Declaration
init
(
uncheckedBounds
bounds
: (
lower
:
Bound
,
upper
:
Bound
))
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
:
CountableRange
<
Bound
>
.
IndexDistance
{
get
}
Declared In
BidirectionalCollection
, Collection
The custom mirror for this instance.
If this type has value semantics, the mirror should be unaffected by subsequent mutations of the instance.
Declaration
var
customMirror
:
Mirror
{
get
}
A textual representation of the range, suitable for debugging.
Declaration
var
debugDescription
:
String
{
get
}
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
.
index
(
of
:
30
) {
(
numbers
[
index
..
<
numbers
.
endIndex
])
}
// Prints "[30, 40, 50]"
If the collection is empty, endIndex
is equal to startIndex
.
Declaration
var
endIndex
:
Bound
{
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
:
CountableRange
<
Bound
>
.
Iterator
.
Element
? {
get
}
Declared In
BidirectionalCollection
, Collection
The indices that are valid for subscripting the range, in ascending order.
Declaration
var
indices
:
CountableRange
<
Bound
>
{
get
}
A Boolean value indicating whether the range contains no elements.
An empty range has equal lower and upper bounds.
let
empty
=
10
..
<
10
(
empty
.
isEmpty
)
// Prints "true"
Declaration
var
isEmpty
:
Bool
{
get
}
Declared In
CountableRange
, BidirectionalCollection
, Collection
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
:
CountableRange
<
Bound
>
.
Iterator
.
Element
? {
get
}
Declared In
BidirectionalCollection
Identical to self
.
Declaration
var
lazy
:
CountableRange
<
Bound
>
{
get
}
Declared In
RandomAccessCollection
, BidirectionalCollection
, Collection
The range's lower bound.
In an empty range, lowerBound
is equal to upperBound
.
Declaration
var
lowerBound
:
Bound
{
get
}
The position of the first element in a nonempty collection.
If the collection is empty, startIndex
is equal to endIndex
.
Declaration
var
startIndex
:
Bound
{
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
BidirectionalCollection
, Collection
, Sequence
The range's upper bound.
upperBound
is not a valid subscript argument and is always
reachable from lowerBound
by zero or more applications of
index(after:)
.
In an empty range, upperBound
is equal to lowerBound
.
Declaration
var
upperBound
:
Bound
{
get
}
5 inherited items hidden. (Show all)
Subscripts
Accesses the element at specified position.
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 range, and must not equal the range's end
index.
Declaration
subscript
(
position
:
Bound
) -
>
Bound
{
get
}
Accesses the subsequence bounded by the given range.
bounds
: A range of the collection's indices. The upper and
lower bounds of the bounds
range must be valid indices of the
collection and bounds.upperBound
must be less than the collection's
end index.
Declaration
subscript
(
bounds
:
ClosedRange
<
Bound
>
) -
>
CountableRange
<
Bound
>
{
get
}
Accesses the subsequence bounded by the given range.
bounds
: A range of the collection's indices. The upper and
lower bounds of the bounds
range must be valid indices of the
collection and bounds.upperBound
must be less than the collection's
end index.
Declaration
subscript
(
bounds
:
CountableClosedRange
<
Bound
>
) -
>
CountableRange
<
Bound
>
{
get
}
Accesses the subsequence bounded by the given range.
bounds
: A range of the range's indices. The upper and lower
bounds of the bounds
range must be valid indices of the collection.
Declaration
subscript
(
bounds
:
CountableRange
<
Bound
>
) -
>
CountableRange
<
Bound
>
{
get
}
Accesses the subsequence bounded by the given range.
bounds
: A range of the range's indices. The upper and lower
bounds of the bounds
range must be valid indices of the collection.
Declaration
subscript
(
bounds
:
Range
<
Bound
>
) -
>
CountableRange
<
Bound
>
{
get
}
Instance Methods
Returns a Boolean value indicating whether two ranges are equal.
Two ranges are equal when they have the same lower and upper bounds. That requirement holds even for empty ranges.
let
x
:
CountableRange
=
5
..
<
15
(
x
==
5
..
<
15
)
// Prints "true"
let
y
:
CountableRange
=
5
..
<
5
(
y
==
15
..
<
15
)
// Prints "false"
Parameters: lhs: A range to compare. rhs: Another range to compare.
Declaration
func
==(
lhs
:
CountableRange
<
Bound
>
,
rhs
:
CountableRange
<
Bound
>
) -
>
Bool
Returns a Boolean value indicating whether a value is included in a range.
You can use this pattern matching operator (~=
) to test whether a value
is included in a range. The following example uses the ~=
operator to
test whether an integer is included in a range of single-digit numbers.
let
chosenNumber
=
3
if
0
..
<
10
~=
chosenNumber
{
(
"\(
chosenNumber
) is a single digit."
)
}
// Prints "3 is a single digit."
The ~=
operator is used internally in case
statements for pattern
matching. When you match against a range in a case
statement, this
operator is called behind the scenes.
switch
chosenNumber
{
case
0
..
<
10
:
(
"\(
chosenNumber
) is a single digit."
)
case
Int.min
..
<
0
:
(
"\(
chosenNumber
) is negative."
)
default
:
(
"\(
chosenNumber
) is positive."
)
}
// Prints "3 is a single digit."
Parameters:
lhs: A range.
rhs: A value to match against lhs
.
Declaration
func
~=(
pattern
:
CountableRange
<
Bound
>
,
value
:
Bound
) -
>
Bool
Returns a copy of this range clamped to the given limiting range.
The bounds of the result are always limited to the bounds of limits
.
For example:
let
x
:
CountableRange
=
0
..
<
20
(
x
.
clamped
(
to
:
10
..
<
1000
))
// Prints "10..<20"
If the two ranges do not overlap, the result is an empty range within the
bounds of limits
.
let
y
:
CountableRange
=
0
..
<
5
(
y
.
clamped
(
to
:
10
..
<
1000
))
// Prints "10..<10"
limits
: The range to clamp the bounds of this range.
Returns: A new range clamped to the bounds of limits
.
Declaration
func
clamped
(
to
limits
:
CountableRange
<
Bound
>
) -
>
CountableRange
<
Bound
>
Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
You can use the predicate to check for an element of a type that
doesn't conform to the Equatable
protocol, such as the
HTTPResponse
enumeration in this example.
enum
HTTPResponse
{
case
ok
case
error
(
Int
)
}
let
lastThreeResponses
: [
HTTPResponse
] = [.
ok
, .
ok
, .
error
(
404
)]
let
hadError
=
lastThreeResponses
.
contains
{
element
in
if
case
.
error
=
element
{
return
true
}
else
{
return
false
}
}
// 'hadError' == true
Alternatively, a predicate can be satisfied by a range of Equatable
elements or a general condition. This example shows how you can check an
array for an expense greater than $100.
let
expenses
= [
21.37
,
55.21
,
9.32
,
10.18
,
388.77
,
11.41
]
let
hasBigPurchase
=
expenses
.
contains
{ $
0
>
100
}
// 'hasBigPurchase' == true
predicate
: A closure that takes an element of the sequence
as its argument and returns a Boolean value that indicates whether
the passed element represents a match.
Returns: true
if the sequence contains an element that satisfies
predicate
; otherwise, false
.
Declaration
func
contains
(
where
predicate
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Bool
Declared In
BidirectionalCollection
, Collection
, 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
func
distance
(
from
start
:
CountableRange
.
Index
,
to
end
:
CountableRange
.
Index
) -
>
CountableRange
.
IndexDistance
Returns a subsequence by skipping elements while predicate
returns
true
and returning the remaining elements.
predicate
: A closure that takes an element of the
sequence as its argument and returns true
if the element should
be skipped or false
if it should be included. Once the predicate
returns false
it will not be called again.
Complexity: O(n), where n is the length of the collection.
Declaration
func
drop
(
while
predicate
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
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
() -
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
, 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
func
dropFirst
(
_
n
:
Int
) -
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
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
() -
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
, 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 n
elements from the end.
Complexity: O(n), where n is the number of elements to drop.
Declaration
func
dropLast
(
_
n
:
Int
) -
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements, using the given predicate as the equivalence test.
At least one of the sequences must be finite.
The predicate must be a equivalence relation over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
areEquivalent(a, a)
is alwaystrue
. (Reflexivity)areEquivalent(a, b)
impliesareEquivalent(b, a)
. (Symmetry)- If
areEquivalent(a, b)
andareEquivalent(b, c)
are bothtrue
, thenareEquivalent(a, c)
is alsotrue
. (Transitivity)
Parameters:
other: A sequence to compare to this sequence.
areEquivalent: A predicate that returns true
if its two arguments
are equivalent; otherwise, false
.
Returns: true
if this sequence and other
contain equivalent items,
using areEquivalent
as the equivalence test; otherwise, false.
See Also: elementsEqual(_:)
Declaration
func
elementsEqual
<
OtherSequence
where
OtherSequence
:
Sequence
,
OtherSequence
.
Iterator
.
Element
==
CountableRange
<
Bound
>
.
Iterator
.
Element
>
(
_
other
:
OtherSequence
,
by
areEquivalent
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
,
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Bool
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.
This example enumerates the characters of the string "Swift" and prints each character along with its place in the string.
for
(
n
,
c
)
in
"Swift"
.
characters
.
enumerated
() {
(
"\(
n
): '\(
c
)'"
)
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"
When enumerating a collection, the integer part of each pair is a counter
for the enumeration, not necessarily the index of the paired value.
These counters can only be used as indices in instances of 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 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
<
CountableRange
<
Bound
>
>
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
In this example, filter
is used to include only names shorter than
five characters.
let
cast
= [
"Vivien"
,
"Marlon"
,
"Kim"
,
"Karl"
]
let
shortNames
=
cast
.
filter
{ $
0
.
characters
.
count
<
5
}
(
shortNames
)
// Prints "["Kim", "Karl"]"
isIncluded
: A closure that takes an element of the
sequence as its argument and returns a Boolean value indicating
whether the element should be included in the returned array.
Returns: An array of the elements that includeElement
allowed.
Declaration
func
filter
(
_
isIncluded
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
[
CountableRange
<
Bound
>
.
Iterator
.
Element
]
Declared In
BidirectionalCollection
, Collection
, 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
func
first
(
where
predicate
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
CountableRange
<
Bound
>
.
Iterator
.
Element
?
Declared In
BidirectionalCollection
, Collection
, Sequence
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
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
ElementOfResult
?)
rethrows
-
>
[
ElementOfResult
]
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.
Use this method to receive a 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.
See Also: joined()
, map(_:)
Declaration
func
flatMap
<
SegmentOfResult
where
SegmentOfResult
:
Sequence
>
(
_
transform
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
SegmentOfResult
)
rethrows
-
>
[
SegmentOfResult
.
Iterator
.
Element
]
Declared In
BidirectionalCollection
, Collection
, Sequence
Calls the given closure on each element in the sequence in the same order
as a for
-in
loop.
The two loops in the following example produce the same output:
let
numberWords
= [
"one"
,
"two"
,
"three"
]
for
word
in
numberWords
{
(
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
func
forEach
(
_
body
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Swift
.
Void
)
rethrows
Declared In
BidirectionalCollection
, Collection
, Sequence
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:)
.
See Also: index(_:offsetBy:limitedBy:)
, formIndex(_:offsetBy:)
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
func
index
(
_
i
:
CountableRange
.
Index
,
offsetBy
n
:
CountableRange
.
IndexDistance
) -
>
CountableRange
.
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.
i
: A valid index of the collection. i
must be less than
endIndex
.
Returns: The index value immediately after i
.
Declaration
func
index
(
after
i
:
CountableRange
.
Index
) -
>
CountableRange
.
Index
Returns the position immediately before the given index.
i
: A valid index of the collection. i
must be greater than
startIndex
.
Returns: The index value immediately before i
.
Declaration
func
index
(
before
i
:
CountableRange
.
Index
) -
>
CountableRange
.
Index
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
.
index
(
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
.
See Also: index(of:)
Declaration
func
index
(
where
predicate
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
CountableRange
<
Bound
>
.
Index
?
Declared In
BidirectionalCollection
, Collection
Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.
The predicate must be a strict weak ordering over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
areInIncreasingOrder(a, a)
is alwaysfalse
. (Irreflexivity)- If
areInIncreasingOrder(a, b)
andareInIncreasingOrder(b, c)
are bothtrue
, thenareInIncreasingOrder(a, c)
is alsotrue
. (Transitive comparability) - Two elements are incomparable if neither is ordered before the other
according to the predicate. If
a
andb
are incomparable, andb
andc
are incomparable, thena
andc
are also incomparable. (Transitive incomparability)
Parameters:
other: A sequence to compare to this sequence.
areInIncreasingOrder: A predicate that returns true
if its first
argument should be ordered before its second argument; otherwise,
false
.
Returns: true
if this sequence precedes other
in a dictionary
ordering as ordered by areInIncreasingOrder
; otherwise, false
.
Note: This method implements the mathematical notion of lexicographical
ordering, which has no connection to Unicode. If you are sorting
strings to present to the end user, use String
APIs that perform
localized comparison instead.
See Also: lexicographicallyPrecedes(_:)
Declaration
func
lexicographicallyPrecedes
<
OtherSequence
where
OtherSequence
:
Sequence
,
OtherSequence
.
Iterator
.
Element
==
CountableRange
<
Bound
>
.
Iterator
.
Element
>
(
_
other
:
OtherSequence
,
by
areInIncreasingOrder
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
,
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Bool
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns an array containing the results of mapping the given closure over the sequence's elements.
In this example, map
is used first to convert the names in the array
to lowercase strings and then to count their characters.
let
cast
= [
"Vivien"
,
"Marlon"
,
"Kim"
,
"Karl"
]
let
lowercaseNames
=
cast
.
map
{ $
0
.
lowercaseString
}
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let
letterCounts
=
cast
.
map
{ $
0
.
characters
.
count
}
// 'letterCounts' == [6, 6, 3, 4]
transform
: A mapping closure. transform
accepts an
element of this sequence as its parameter and returns a transformed
value of the same or of a different type.
Returns: An array containing the transformed elements of this
sequence.
Declaration
func
map
<
T
>
(
_
transform
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
T
)
rethrows
-
>
[
T
]
Declared In
BidirectionalCollection
, Collection
, 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
.
See Also: max()
Declaration
@
warn_unqualified_access
func
max
(
by
areInIncreasingOrder
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
,
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
CountableRange
<
Bound
>
.
Iterator
.
Element
?
Declared In
BidirectionalCollection
, Collection
, 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
.
See Also: min()
Declaration
func
min
(
by
areInIncreasingOrder
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
,
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
CountableRange
<
Bound
>
.
Iterator
.
Element
?
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns a Boolean value indicating whether this range and the given range contain an element in common.
This example shows two overlapping ranges:
let
x
:
CountableRange
=
0
..
<
20
(
x
.
overlaps
(
10
...
1000
as
ClosedRange
))
// Prints "true"
Because a half-open range does not include its upper bound, the ranges in the following example do not overlap:
let
y
:
ClosedRange
=
20
..
<
30
(
x
.
overlaps
(
y
))
// Prints "false"
other
: A range to check for elements in common.
Returns: true
if this range and other
have at least one element in
common; otherwise, false
.
Declaration
func
overlaps
(
_
other
:
ClosedRange
<
Bound
>
) -
>
Bool
Returns a Boolean value indicating whether this range and the given range contain an element in common.
This example shows two overlapping ranges:
let
x
:
CountableRange
=
0
..
<
20
(
x
.
overlaps
(
10
...
1000
as
CountableClosedRange
))
// Prints "true"
Because a half-open range does not include its upper bound, the ranges in the following example do not overlap:
let
y
:
CountableClosedRange
=
20
..
<
30
(
x
.
overlaps
(
y
))
// Prints "false"
other
: A range to check for elements in common.
Returns: true
if this range and other
have at least one element in
common; otherwise, false
.
Declaration
func
overlaps
(
_
other
:
CountableClosedRange
<
Bound
>
) -
>
Bool
Returns a Boolean value indicating whether this range and the given range contain an element in common.
This example shows two overlapping ranges:
let
x
:
CountableRange
=
0
..
<
20
(
x
.
overlaps
(
10
..
<
1000
as
CountableRange
))
// Prints "true"
Because a half-open range does not include its upper bound, the ranges in the following example do not overlap:
let
y
:
CountableRange
=
20
..
<
30
(
x
.
overlaps
(
y
))
// Prints "false"
other
: A range to check for elements in common.
Returns: true
if this range and other
have at least one element in
common; otherwise, false
.
Declaration
func
overlaps
(
_
other
:
CountableRange
<
Bound
>
) -
>
Bool
Returns a Boolean value indicating whether this range and the given range contain an element in common.
This example shows two overlapping ranges:
let
x
:
CountableRange
=
0
..
<
20
(
x
.
overlaps
(
10
..
<
1000
as
Range
))
// Prints "true"
Because a half-open range does not include its upper bound, the ranges in the following example do not overlap:
let
y
:
Range
=
20
..
<
30
(
x
.
overlaps
(
y
))
// Prints "false"
other
: A range to check for elements in common.
Returns: true
if this range and other
have at least one element in
common; otherwise, false
.
Declaration
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
func
prefix
(
_
maxLength
:
Int
) -
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
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
.
index
(
of
:
40
) {
(
numbers
.
prefix
(
through
:
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)
See Also: prefix(upTo:)
Declaration
func
prefix
(
through
position
:
CountableRange
<
Bound
>
.
Index
) -
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
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
.
index
(
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 "[]"
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)
See Also: prefix(through:)
Declaration
func
prefix
(
upTo
end
:
CountableRange
<
Bound
>
.
Index
) -
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
Returns a subsequence containing the initial elements until predicate
returns false
and skipping the remaining elements.
predicate
: A closure that takes an element of the
sequence as its argument and returns true
if the element should
be included or false
if it should be excluded. Once the predicate
returns false
it will not be called again.
Complexity: O(n), where n is the length of the collection.
Declaration
func
prefix
(
while
predicate
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
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
,
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Result
)
rethrows
-
>
Result
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns a view presenting the elements of the collection in reverse order.
You can reverse a collection without allocating new space for its
elements by calling this reversed()
method. A
ReversedRandomAccessCollection
instance wraps an underlying collection
and provides access to its elements in reverse order. This example
prints the elements of an array in reverse order:
let
numbers
= [
3
,
5
,
7
]
for
number
in
numbers
.
reversed
() {
(
number
)
}
// Prints "7"
// Prints "5"
// Prints "3"
If you need a reversed collection of the same type, you may be able to
use the collection's sequence-based or collection-based initializer. For
example, to get the reversed version of an array, initialize a new
Array
instance from the result of this reversed()
method.
let
reversedNumbers
=
Array
(
numbers
.
reversed
())
(
reversedNumbers
)
// Prints "[7, 5, 3]"
Complexity: O(1)
Declaration
func
reversed
() -
>
ReversedRandomAccessCollection
<
CountableRange
<
Bound
>
>
Declared In
RandomAccessCollection
, BidirectionalCollection
, Collection
, Sequence
Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.
When you want to sort a sequence of elements that don't conform to
the Comparable
protocol, pass a predicate to this method that returns
true
when the first element passed should be ordered before the
second. The elements of the resulting array are ordered according to the
given predicate.
The predicate must be a strict weak ordering over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
areInIncreasingOrder(a, a)
is alwaysfalse
. (Irreflexivity)- If
areInIncreasingOrder(a, b)
andareInIncreasingOrder(b, c)
are bothtrue
, thenareInIncreasingOrder(a, c)
is alsotrue
. (Transitive comparability) - Two elements are incomparable if neither is ordered before the other
according to the predicate. If
a
andb
are incomparable, andb
andc
are incomparable, thena
andc
are also incomparable. (Transitive incomparability)
The sorting algorithm is not stable. A nonstable sort may change the
relative order of elements for which areInIncreasingOrder
does not
establish an order.
In the following example, the predicate provides an ordering for an array
of a custom HTTPResponse
type. The predicate orders errors before
successes and sorts the error responses by their error code.
enum
HTTPResponse
{
case
ok
case
error
(
Int
)
}
let
responses
: [
HTTPResponse
] = [.
error
(
500
), .
ok
, .
ok
, .
error
(
404
), .
error
(
403
)]
let
sortedResponses
=
responses
.
sorted
{
switch
($
0
, $
1
) {
// Order errors by code
case
let
(.
error
(
aCode
), .
error
(
bCode
)):
return
aCode
<
bCode
// All successes are equivalent, so none is before any other
case
(.
ok
, .
ok
):
return
false
// Order errors before successes
case
(.
error
, .
ok
):
return
true
case
(.
ok
, .
error
):
return
false
}
}
(
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.
See Also: sorted()
Declaration
func
sorted
(
by
areInIncreasingOrder
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
,
CountableRange
<
Bound
>
.
Iterator
.
Element
) -
>
Bool
) -
>
[
CountableRange
<
Bound
>
.
Iterator
.
Element
]
Declared In
BidirectionalCollection
, Collection
, 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
.
characters
.
split
(
whereSeparator
: { $
0
==
" "
})
.
map
(
String
.
init
))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
The second example passes 1
for the maxSplits
parameter, so the
original string is split just once, into two new strings.
(
line
.
characters
.
split
(
maxSplits
:
1
,
whereSeparator
: { $
0
==
" "
}
).
map
(
String
.
init
))
// Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
The final example passes false
for the omittingEmptySubsequences
parameter, so the returned array contains empty strings where spaces
were repeated.
(
line
.
characters
.
split
(
omittingEmptySubsequences
:
false
,
whereSeparator
: { $
0
==
" "
})
.
map
(
String
.
init
))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
Parameters:
maxSplits: The maximum number of times to split the 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
func
split
(
maxSplits
:
Int
=
default
,
omittingEmptySubsequences
:
Bool
=
default
,
whereSeparator
isSeparator
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
[
CountableRange
<
Bound
>
.
SubSequence
]
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns a Boolean value indicating whether the initial elements of the sequence are equivalent to the elements in another sequence, using the given predicate as the equivalence test.
The predicate must be a equivalence relation over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
areEquivalent(a, a)
is alwaystrue
. (Reflexivity)areEquivalent(a, b)
impliesareEquivalent(b, a)
. (Symmetry)- If
areEquivalent(a, b)
andareEquivalent(b, c)
are bothtrue
, thenareEquivalent(a, c)
is alsotrue
. (Transitivity)
Parameters:
possiblePrefix: A sequence to compare to this sequence.
areEquivalent: A predicate that returns true
if its two arguments
are equivalent; otherwise, false
.
Returns: true
if the initial elements of the sequence are equivalent
to the elements of possiblePrefix
; otherwise, false
. If
possiblePrefix
has no elements, the return value is true
.
See Also: starts(with:)
Declaration
func
starts
<
PossiblePrefix
where
PossiblePrefix
:
Sequence
,
PossiblePrefix
.
Iterator
.
Element
==
CountableRange
<
Bound
>
.
Iterator
.
Element
>
(
with
possiblePrefix
:
PossiblePrefix
,
by
areEquivalent
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
,
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Bool
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns a subsequence, up to the given maximum length, containing the final elements of the collection.
If the maximum length exceeds the number of elements in the collection, the result contains the entire collection.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
suffix
(
2
))
// Prints "[4, 5]"
(
numbers
.
suffix
(
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 terminating at the end of the collection with at
most maxLength
elements.
Complexity: O(n), where n is equal to maxLength
.
Declaration
func
suffix
(
_
maxLength
:
Int
) -
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
, Sequence
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
.
index
(
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 "[]"
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
func
suffix
(
from
start
:
CountableRange
<
Bound
>
.
Index
) -
>
CountableRange
<
Bound
>
.
SubSequence
Declared In
BidirectionalCollection
, Collection
29 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 Base.Iterator == Iterator
Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
In this example, filter
is used to include only names shorter than five
characters.
let
cast
= [
"Vivien"
,
"Marlon"
,
"Kim"
,
"Karl"
]
let
shortNames
=
cast
.
filter
{ $
0
.
characters
.
count
<
5
}
(
shortNames
)
// Prints "["Kim", "Karl"]"
includeElement
: A closure that takes an element of the
sequence as its argument and returns a Boolean value indicating
whether the element should be included in the returned array.
Returns: An array of the elements that includeElement
allowed.
Declaration
func
filter
(
_
isIncluded
: (
CountableRange
<
Bound
>
.
Base
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
[
CountableRange
<
Bound
>
.
Base
.
Iterator
.
Element
]
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns an iterator over the elements of this sequence.
Declaration
func
makeIterator
() -
>
CountableRange
<
Bound
>
.
Base
.
Iterator
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns an array containing the results of mapping the given closure over the sequence's elements.
In this example, map
is used first to convert the names in the array to
lowercase strings and then to count their characters.
let
cast
= [
"Vivien"
,
"Marlon"
,
"Kim"
,
"Karl"
]
let
lowercaseNames
=
cast
.
map
{ $
0
.
lowercaseString
}
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let
letterCounts
=
cast
.
map
{ $
0
.
characters
.
count
}
// 'letterCounts' == [6, 6, 3, 4]
transform
: A mapping closure. transform
accepts an
element of this sequence as its parameter and returns a transformed
value of the same or of a different type.
Returns: An array containing the transformed elements of this
sequence.
Declaration
func
map
<
T
>
(
_
transform
: (
CountableRange
<
Bound
>
.
Base
.
Iterator
.
Element
)
throws
-
>
T
)
rethrows
-
>
[
T
]
Declared In
BidirectionalCollection
, Collection
, Sequence
3 inherited items hidden. (Show all)
Where Index : Strideable, Indices == CountableRange, Index.Stride == IndexDistance, Indices.Index == Index, Indices.IndexDistance == IndexDistance, Indices.Indices == CountableRange, Indices.Iterator == IndexingIterator>, Indices.SubSequence == CountableRange, Indices._Element == Index, Indices.Indices.Index == Index, Indices.Indices.IndexDistance == IndexDistance, Indices.Indices.Indices == CountableRange, Indices.Indices.Iterator == IndexingIterator>, Indices.Indices.SubSequence == CountableRange, Indices.Indices._Element == Index, Indices.Iterator.Element == Index, Indices.SubSequence.Index == Index, Indices.SubSequence.IndexDistance == IndexDistance, Indices.SubSequence.Indices == CountableRange, Indices.SubSequence.Iterator == IndexingIterator>, Indices.SubSequence.SubSequence == CountableRange, Indices.SubSequence._Element == Index, Indices.Indices.Indices.Index == Index, Indices.Indices.Indices.IndexDistance == IndexDistance, Indices.Indices.Indices.Iterator == IndexingIterator>, Indices.Indices.Indices.SubSequence == CountableRange, Indices.Indices.Indices._Element == Index, Indices.Indices.Iterator.Element == Index, Indices.Indices.SubSequence.Index == Index, Indices.Indices.SubSequence.Iterator == IndexingIterator>, Indices.Indices.SubSequence.SubSequence == CountableRange, Indices.Indices.SubSequence._Element == Index, Indices.SubSequence.Indices.Index == Index, Indices.SubSequence.Indices.IndexDistance == IndexDistance, Indices.SubSequence.Indices.Iterator == IndexingIterator>, Indices.SubSequence.Indices.SubSequence == CountableRange, Indices.SubSequence.Indices._Element == Index, Indices.SubSequence.Iterator.Element == Index, Indices.SubSequence.SubSequence.Index == Index, Indices.SubSequence.SubSequence.Iterator == IndexingIterator>, Indices.SubSequence.SubSequence.SubSequence == CountableRange, Indices.SubSequence.SubSequence._Element == Index, Indices.Indices.Indices.Iterator.Element == Index, Indices.Indices.SubSequence.Iterator.Element == Index, Indices.SubSequence.Indices.Iterator.Element == Index, Indices.SubSequence.SubSequence.Iterator.Element == Index
The indices that are valid for subscripting the collection, in ascending order.
Declaration
var
indices
:
CountableRange
<
CountableRange
<
Bound
>
.
Index
>
{
get
}
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
func
distance
(
from
start
:
CountableRange
<
Bound
>
.
Index
,
to
end
:
CountableRange
<
Bound
>
.
Index
) -
>
CountableRange
<
Bound
>
.
Index
.
Stride
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
func
index
(
_
i
:
CountableRange
<
Bound
>
.
Index
,
offsetBy
n
:
CountableRange
<
Bound
>
.
Index
.
Stride
) -
>
CountableRange
<
Bound
>
.
Index
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
func
index
(
after
i
:
CountableRange
<
Bound
>
.
Index
) -
>
CountableRange
<
Bound
>
.
Index
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
func
index
(
before
i
:
CountableRange
<
Bound
>
.
Index
) -
>
CountableRange
<
Bound
>
.
Index
Declared In
RandomAccessCollection
5 inherited items hidden. (Show all)
Where Indices == DefaultBidirectionalIndices, Indices.Index == Index, Indices.IndexDistance == Int, Indices.Indices == DefaultBidirectionalIndices, Indices.Iterator == IndexingIterator>, Indices.SubSequence == DefaultBidirectionalIndices, Indices._Element == Index, Indices.IndexDistance.IntegerLiteralType == Int, Indices.IndexDistance.Stride == Int, Indices.IndexDistance._DisabledRangeIndex == Int._DisabledRangeIndex, Indices.Indices.Index == Index, Indices.Indices.IndexDistance == Int, Indices.Indices.Iterator == IndexingIterator>, Indices.Indices.SubSequence == DefaultBidirectionalIndices, Indices.Indices._Element == Index, Indices.Iterator.Element == Index, Indices.SubSequence.Index == Index, Indices.SubSequence.Iterator == IndexingIterator>, Indices.SubSequence.SubSequence == DefaultBidirectionalIndices, Indices.SubSequence._Element == Index, Indices.IndexDistance.Stride.IntegerLiteralType == Int, Indices.Indices.IndexDistance.IntegerLiteralType == Int, Indices.Indices.IndexDistance.Stride == Int, Indices.Indices.IndexDistance._DisabledRangeIndex == Int._DisabledRangeIndex, Indices.Indices.Iterator.Element == Index, Indices.SubSequence.Iterator.Element == Index, Indices.Indices.IndexDistance.Stride.IntegerLiteralType == Int
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
:
DefaultBidirectionalIndices
<
CountableRange
<
Bound
>
>
{
get
}
Declared In
BidirectionalCollection
1 inherited item hidden. (Show all)
Where Indices == DefaultIndices, Indices.Index == Index, Indices.IndexDistance == Int, Indices.Iterator == IndexingIterator>, Indices.SubSequence == DefaultIndices, Indices._Element == Index, Indices.IndexDistance.IntegerLiteralType == Int, Indices.IndexDistance.Stride == Int, Indices.IndexDistance._DisabledRangeIndex == Int._DisabledRangeIndex, Indices.Iterator.Element == Index, Indices.IndexDistance.Stride.IntegerLiteralType == Int
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
<
CountableRange
<
Bound
>
>
{
get
}
Declared In
BidirectionalCollection
, Collection
1 inherited item hidden. (Show all)
Where Iterator == IndexingIterator, Iterator.Element == _Element
Returns an iterator over the elements of the collection.
Declaration
func
makeIterator
() -
>
IndexingIterator
<
CountableRange
<
Bound
>
>
Declared In
BidirectionalCollection
, Collection
1 inherited item hidden. (Show all)
Where Iterator == Self
Returns an iterator over the elements of this sequence.
Declaration
func
makeIterator
() -
>
CountableRange
<
Bound
>
Declared In
BidirectionalCollection
, Collection
, Sequence
1 inherited item hidden. (Show all)
Where Iterator.Element : BidirectionalCollection
Returns the elements of this collection of collections, 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 collection of collections.
See Also: flatMap(_:)
, joined(separator:)
Declaration
func
joined
() -
>
FlattenBidirectionalCollection
<
CountableRange
<
Bound
>
>
Declared In
BidirectionalCollection
1 inherited item hidden. (Show all)
Where Iterator.Element : Collection
Returns the elements of this collection of collections, 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 collection of collections.
See Also: flatMap(_:)
, joined(separator:)
Declaration
func
joined
() -
>
FlattenCollection
<
CountableRange
<
Bound
>
>
Declared In
BidirectionalCollection
, Collection
1 inherited item hidden. (Show all)
Where Iterator.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.
See Also: lexicographicallyPrecedes(_:by:)
Declaration
func
lexicographicallyPrecedes
<
OtherSequence
where
OtherSequence
:
Sequence
,
OtherSequence
.
Iterator
.
Element
==
CountableRange
<
Bound
>
.
Iterator
.
Element
>
(
_
other
:
OtherSequence
) -
>
Bool
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns the maximum 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
greatestHeight
=
heights
.
max
()
(
greatestHeight
)
// Prints "Optional(67.5)"
Returns: The sequence's maximum element. If the sequence has no
elements, returns nil
.
See Also: max(by:)
Declaration
@
warn_unqualified_access
func
max
() -
>
CountableRange
<
Bound
>
.
Iterator
.
Element
?
Declared In
BidirectionalCollection
, Collection
, 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
.
See Also: min(by:)
Declaration
@
warn_unqualified_access
func
min
() -
>
CountableRange
<
Bound
>
.
Iterator
.
Element
?
Declared In
BidirectionalCollection
, Collection
, Sequence
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.
See Also: sorted(by:)
Declaration
func
sorted
() -
>
[
CountableRange
<
Bound
>
.
Iterator
.
Element
]
Declared In
BidirectionalCollection
, Collection
, Sequence
4 inherited items hidden. (Show all)
Where Iterator.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
func
contains
(
_
element
:
CountableRange
<
Bound
>
.
Iterator
.
Element
) -
>
Bool
Declared In
BidirectionalCollection
, Collection
, 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.
See Also: elementsEqual(_:by:)
Declaration
func
elementsEqual
<
OtherSequence
where
OtherSequence
:
Sequence
,
OtherSequence
.
Iterator
.
Element
==
CountableRange
<
Bound
>
.
Iterator
.
Element
>
(
_
other
:
OtherSequence
) -
>
Bool
Declared In
BidirectionalCollection
, Collection
, Sequence
Returns the first index where the specified value appears in the collection.
After using index(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
.
index
(
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
.
See Also: index(where:)
Declaration
func
index
(
of
element
:
CountableRange
<
Bound
>
.
Iterator
.
Element
) -
>
CountableRange
<
Bound
>
.
Index
?
Declared In
BidirectionalCollection
, Collection
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
.
characters
.
split
(
separator
:
" "
)
.
map
(
String
.
init
))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
The second example passes 1
for the maxSplits
parameter, so the
original string is split just once, into two new strings.
(
line
.
characters
.
split
(
separator
:
" "
,
maxSplits
:
1
)
.
map
(
String
.
init
))
// Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
The final example passes false
for the omittingEmptySubsequences
parameter, so the returned array contains empty strings where spaces
were repeated.
(
line
.
characters
.
split
(
separator
:
" "
,
omittingEmptySubsequences
:
false
)
.
map
(
String
.
init
))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
Parameters:
separator: The element that should be split upon.
maxSplits: The maximum number of times to split the 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
func
split
(
separator
:
CountableRange
<
Bound
>
.
Iterator
.
Element
,
maxSplits
:
Int
=
default
,
omittingEmptySubsequences
:
Bool
=
default
) -
>
[
CountableRange
<
Bound
>
.
SubSequence
]
Declared In
BidirectionalCollection
, Collection
, 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
.
See Also: starts(with:by:)
Declaration
func
starts
<
PossiblePrefix
where
PossiblePrefix
:
Sequence
,
PossiblePrefix
.
Iterator
.
Element
==
CountableRange
<
Bound
>
.
Iterator
.
Element
>
(
with
possiblePrefix
:
PossiblePrefix
) -
>
Bool
Declared In
BidirectionalCollection
, Collection
, Sequence
5 inherited items hidden. (Show all)
Where Iterator.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.
See Also: flatMap(_:)
, joined(separator:)
Declaration
func
joined
() -
>
FlattenSequence
<
CountableRange
<
Bound
>
>
Declared In
BidirectionalCollection
, Collection
, 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.
See Also: joined()
Declaration
func
joined
<
Separator
where
Separator
:
Sequence
,
Separator
.
Iterator
.
Element
==
CountableRange
<
Bound
>
.
Iterator
.
Element
.
Iterator
.
Element
>
(
separator
:
Separator
) -
>
JoinedSequence
<
CountableRange
<
Bound
>
>
Declared In
BidirectionalCollection
, Collection
, Sequence
2 inherited items hidden. (Show all)
Where Iterator.Element == String
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
BidirectionalCollection
, Collection
, Sequence
1 inherited item hidden. (Show all)
Where SubSequence : Sequence, SubSequence.SubSequence == SubSequence, SubSequence.Iterator.Element == Iterator.Element
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.
See Also: prefix(while:)
Declaration
func
drop
(
while
predicate
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
AnySequence
<
CountableRange
<
Bound
>
.
Iterator
.
Element
>
Declared In
BidirectionalCollection
, Collection
, 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
<
CountableRange
<
Bound
>
.
Iterator
.
Element
>
Declared In
BidirectionalCollection
, Collection
, 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
<
CountableRange
<
Bound
>
.
Iterator
.
Element
>
Declared In
BidirectionalCollection
, Collection
, 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
<
CountableRange
<
Bound
>
.
Iterator
.
Element
>
Declared In
BidirectionalCollection
, Collection
, 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.
See Also: drop(while:)
Declaration
func
prefix
(
while
predicate
: (
CountableRange
<
Bound
>
.
Iterator
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
AnySequence
<
CountableRange
<
Bound
>
.
Iterator
.
Element
>
Declared In
BidirectionalCollection
, Collection
, Sequence
5 inherited items hidden. (Show all)
Where SubSequence == BidirectionalSlice, SubSequence.Index == Index, SubSequence.IndexDistance == IndexDistance, SubSequence.Indices == DefaultBidirectionalIndices>, SubSequence.Iterator == IndexingIterator>, SubSequence.SubSequence == BidirectionalSlice, SubSequence._Element == _Element, SubSequence.Indices.Index == Index, SubSequence.Indices.IndexDistance == Int, SubSequence.Indices.Iterator == IndexingIterator>>, SubSequence.Indices.SubSequence == DefaultBidirectionalIndices>, SubSequence.Indices._Element == Index, SubSequence.Iterator.Element == _Element, SubSequence.SubSequence.Index == Index, SubSequence.SubSequence.Iterator == IndexingIterator>, SubSequence.SubSequence.SubSequence == BidirectionalSlice, SubSequence.SubSequence._Element == _Element, SubSequence.Indices.IndexDistance.IntegerLiteralType == Int, SubSequence.Indices.IndexDistance.Stride == Int, SubSequence.Indices.IndexDistance._DisabledRangeIndex == Int._DisabledRangeIndex, SubSequence.Indices.Iterator.Element == Index, SubSequence.SubSequence.Iterator.Element == _Element, SubSequence.Indices.IndexDistance.Stride.IntegerLiteralType == Int
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
.
index
(
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.
Declaration
subscript
(
bounds
:
Range
<
CountableRange
<
Bound
>
.
Index
>
) -
>
BidirectionalSlice
<
CountableRange
<
Bound
>
>
{
get
}
Declared In
BidirectionalCollection
1 inherited item hidden. (Show all)
Where SubSequence == RandomAccessSlice, SubSequence.Index == Index, SubSequence.IndexDistance == IndexDistance, SubSequence.Indices == DefaultRandomAccessIndices>, SubSequence.Iterator == IndexingIterator>, SubSequence.SubSequence == RandomAccessSlice, SubSequence._Element == _Element, SubSequence.Indices.Index == Index, SubSequence.Indices.IndexDistance == Int, SubSequence.Indices.Indices == DefaultRandomAccessIndices>, SubSequence.Indices.Iterator == IndexingIterator>>, SubSequence.Indices.SubSequence == DefaultRandomAccessIndices>, SubSequence.Indices._Element == Index, SubSequence.Iterator.Element == _Element, SubSequence.SubSequence.Index == Index, SubSequence.SubSequence.IndexDistance == IndexDistance, SubSequence.SubSequence.Indices == DefaultRandomAccessIndices>, SubSequence.SubSequence.Iterator == IndexingIterator>, SubSequence.SubSequence.SubSequence == RandomAccessSlice, SubSequence.SubSequence._Element == _Element, SubSequence.Indices.IndexDistance.IntegerLiteralType == Int, SubSequence.Indices.IndexDistance.Stride == Int, SubSequence.Indices.IndexDistance._DisabledRangeIndex == Int._DisabledRangeIndex, SubSequence.Indices.Indices.Index == Index, SubSequence.Indices.Indices.IndexDistance == Int, SubSequence.Indices.Indices.Iterator == IndexingIterator>>, SubSequence.Indices.Indices.SubSequence == DefaultRandomAccessIndices>, SubSequence.Indices.Indices._Element == Index, SubSequence.Indices.Iterator.Element == Index, SubSequence.Indices.SubSequence.Index == Index, SubSequence.Indices.SubSequence.Iterator == IndexingIterator>>, SubSequence.Indices.SubSequence.SubSequence == DefaultRandomAccessIndices>, SubSequence.Indices.SubSequence._Element == Index, SubSequence.SubSequence.Indices.Index == Index, SubSequence.SubSequence.Indices.IndexDistance == Int, SubSequence.SubSequence.Indices.Iterator == IndexingIterator>>, SubSequence.SubSequence.Indices.SubSequence == DefaultRandomAccessIndices>, SubSequence.SubSequence.Indices._Element == Index, SubSequence.SubSequence.Iterator.Element == _Element, SubSequence.SubSequence.SubSequence.Index == Index, SubSequence.SubSequence.SubSequence.Iterator == IndexingIterator>, SubSequence.SubSequence.SubSequence.SubSequence == RandomAccessSlice, SubSequence.SubSequence.SubSequence._Element == _Element, SubSequence.Indices.IndexDistance.Stride.IntegerLiteralType == Int, SubSequence.Indices.Indices.IndexDistance.IntegerLiteralType == Int, SubSequence.Indices.Indices.IndexDistance.Stride == Int, SubSequence.Indices.Indices.IndexDistance._DisabledRangeIndex == Int._DisabledRangeIndex, SubSequence.Indices.Indices.Iterator.Element == Index, SubSequence.Indices.SubSequence.Iterator.Element == Index, SubSequence.SubSequence.Indices.IndexDistance.IntegerLiteralType == Int, SubSequence.SubSequence.Indices.IndexDistance.Stride == Int, SubSequence.SubSequence.Indices.IndexDistance._DisabledRangeIndex == Int._DisabledRangeIndex, SubSequence.SubSequence.Indices.Iterator.Element == Index, SubSequence.SubSequence.SubSequence.Iterator.Element == _Element, SubSequence.Indices.Indices.IndexDistance.Stride.IntegerLiteralType == Int, SubSequence.SubSequence.Indices.IndexDistance.Stride.IntegerLiteralType == Int
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
.
index
(
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.
Declaration
subscript
(
bounds
:
Range
<
CountableRange
<
Bound
>
.
Index
>
) -
>
RandomAccessSlice
<
CountableRange
<
Bound
>
>
{
get
}
Declared In
RandomAccessCollection
1 inherited item hidden. (Show all)
Where SubSequence == Self
Removes and returns the first element of the collection.
Returns: The first element of the collection if the collection is
not empty; otherwise, nil
.
Complexity: O(1)
Declaration
mutating
func
popFirst
() -
>
CountableRange
<
Bound
>
.
Iterator
.
Element
?
Declared In
BidirectionalCollection
, Collection
Removes and returns the last element of the collection.
You can use popLast()
to remove the last element of a collection that
might be empty. The removeLast()
method must be used only on a
nonempty collection.
Returns: The last element of the collection if the collection has one
or more elements; otherwise, nil
.
Complexity: O(1).
See Also: removeLast()
Declaration
mutating
func
popLast
() -
>
CountableRange
<
Bound
>
.
Iterator
.
Element
?
Declared In
BidirectionalCollection
Removes and returns the first element of the collection.
The collection must not be empty.
Returns: The first element of the collection.
Complexity: O(1)
See Also: popFirst()
Declaration
mutating
func
removeFirst
() -
>
CountableRange
<
Bound
>
.
Iterator
.
Element
Declared In
BidirectionalCollection
, Collection
Removes the specified number of elements from the beginning of the collection.
n
: The number of elements to remove. n
must be greater than
or equal to zero, and must be less than or equal to the number of
elements in the collection.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n).
Declaration
mutating
func
removeFirst
(
_
n
:
Int
)
Declared In
BidirectionalCollection
, Collection
Removes and returns the last element of the collection.
The collection must not be empty. To remove the last element of a
collection that might be empty, use the popLast()
method instead.
Returns: The last element of the collection.
Complexity: O(1)
See Also: popLast()
Declaration
mutating
func
removeLast
() -
>
CountableRange
<
Bound
>
.
Iterator
.
Element
Declared In
BidirectionalCollection
Removes the given number of elements from the end of the collection.
n
: The number of elements to remove. n
must be greater
than or equal to zero, and must be 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
mutating
func
removeLast
(
_
n
:
Int
)
Declared In
BidirectionalCollection
6 inherited items hidden. (Show all)
Where SubSequence == Slice, SubSequence.Index == Index, SubSequence.Iterator == IndexingIterator>, SubSequence.SubSequence == Slice, SubSequence._Element == _Element, SubSequence.Iterator.Element == _Element
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
.
index
(
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
subscript
(
bounds
:
Range
<
CountableRange
<
Bound
>
.
Index
>
) -
>
Slice
<
CountableRange
<
Bound
>
>
{
get
}
Declared In
BidirectionalCollection
, Collection
1 inherited item hidden. (Show all)
A half-open range that forms a collection of consecutive values.
You create a
CountableRange
instance by using the half-open range operator (..<
).The associated
Bound
type is both the element and index type ofCountableRange
. Each element of the range is its own corresponding index. The lower bound of aCountableRange
instance is its start index, and the upper bound is its end index.If the
Bound
type has a maximal value, it can serve as an upper bound but can never be contained in aCountableRange<Bound>
instance. For example, aCountableRange<Int8>
instance can useInt8.max
as its upper bound, but it can't represent a range that includesInt8.max
.If you need to create a range that includes the maximal value of its
Bound
type, see theCountableClosedRange
type.You can create a countable range over any type that conforms to the
Strideable
protocol and uses an integer as its associatedStride
type. By default, Swift's integer and pointer types are usable as the bounds of a countable range.Because floating-point types such as
Float
andDouble
are their ownStride
types, they cannot be used as the bounds of a countable range. If you need to test whether values are contained within an interval bound by floating-point values, see theRange
type. If you need to iterate over consecutive floating-point values, see thestride(from:to:by:)
function.Integer Index Ambiguity
Because each element of a
CountableRange
instance is its own index, for the range(-99..<100)
the element at index0
is0
. This is an unexpected result for those accustomed to zero-based collection indices, who might expect the result to be-99
. To prevent this confusion, in a context whereBound
is known to be an integer type, subscripting directly is a compile-time error:However, subscripting that range still works in a generic context:
See Also:
CountableClosedRange
,Range
,ClosedRange