struct
Dictionary
A collection whose elements are key-value pairs.
Inheritance | Collection, CustomDebugStringConvertible, CustomReflectable, CustomStringConvertible, ExpressibleByDictionaryLiteral, Sequence |
---|---|
Associated Types |
This associated type appears as a requirement in the |
Nested Types | Dictionary.Keys, Dictionary.Values, Dictionary.Index, Dictionary.Iterator |
A dictionary is a type of hash table, providing fast access to the entries it contains. Each entry in the table is identified using its key, which is a hashable type such as a string or number. You use that key to retrieve the corresponding value, which can be any object. In other languages, similar data types are known as hashes or associated arrays.
Create a new dictionary by using a dictionary literal. A dictionary literal is a comma-separated list of key-value pairs, in which a colon separates each key from its associated value, surrounded by square brackets. You can assign a dictionary literal to a variable or constant or pass it to a function that expects a dictionary.
Here's how you would create a dictionary of HTTP response codes and their related messages:
var
responseMessages
= [
200
:
"OK"
,
403
:
"Access forbidden"
,
404
:
"File not found"
,
500
:
"Internal server error"
]
The responseMessages
variable is inferred to have type [Int: String]
.
The Key
type of the dictionary is Int
, and the Value
type of the
dictionary is String
.
To create a dictionary with no key-value pairs, use an empty dictionary
literal ([:]
).
Any type that conforms to the Hashable
protocol can be used as a
dictionary's Key
type, including all of Swift's basic types. You can use
your own custom types as dictionary keys by making them conform to the
Hashable
protocol.
Getting and Setting Dictionary Values
The most common way to access values in a dictionary is to use a key as a subscript. Subscripting with a key takes the following form:
(
responseMessages
[
200
])
// Prints "Optional("OK")"
Subscripting a dictionary with a key returns an optional value, because a dictionary might not hold a value for the key that you use in the subscript.
The next example uses key-based subscripting of the responseMessages
dictionary with two keys that exist in the dictionary and one that does
not.
let
httpResponseCodes
= [
200
,
403
,
301
]
for
code
in
httpResponseCodes
{
if
let
message
=
responseMessages
[
code
] {
(
"Response \(
code
): \(
message
)"
)
}
else
{
(
"Unknown response \(
code
)"
)
}
}
// Prints "Response 200: OK"
// Prints "Response 403: Access Forbidden"
// Prints "Unknown response 301"
You can also update, modify, or remove keys and values from a dictionary using the key-based subscript. To add a new key-value pair, assign a value to a key that isn't yet a part of the dictionary.
responseMessages
[
301
] =
"Moved permanently"
(
responseMessages
[
301
])
// Prints "Optional("Moved permanently")"
Update an existing value by assigning a new value to a key that already
exists in the dictionary. If you assign nil
to an existing key, the key
and its associated value are removed. The following example updates the
value for the 404
code to be simply "Not found" and removes the
key-value pair for the 500
code entirely.
responseMessages
[
404
] =
"Not found"
responseMessages
[
500
] =
nil
(
responseMessages
)
// Prints "[301: "Moved permanently", 200: "OK", 403: "Access forbidden", 404: "Not found"]"
In a mutable Dictionary
instance, you can modify in place a value that
you've accessed through a keyed subscript. The code sample below declares a
dictionary called interestingNumbers
with string keys and values that
are integer arrays, then sorts each array in-place in descending order.
var
interestingNumbers
= [
"primes"
: [
2
,
3
,
5
,
7
,
11
,
13
,
17
],
"triangular"
: [
1
,
3
,
6
,
10
,
15
,
21
,
28
],
"hexagonal"
: [
1
,
6
,
15
,
28
,
45
,
66
,
91
]]
for
key
in
interestingNumbers
.
keys
{
interestingNumbers
[
key
]?.
sort
(
by
:
>
)
}
(
interestingNumbers
[
"primes"
]!)
// Prints "[17, 13, 11, 7, 5, 3, 2]"
Iterating Over the Contents of a Dictionary
Every dictionary is an unordered collection of key-value pairs. You can
iterate over a dictionary using a for
-in
loop, decomposing each
key-value pair into the elements of a tuple.
let
imagePaths
= [
"star"
:
"/glyphs/star.png"
,
"portrait"
:
"/images/content/portrait.jpg"
,
"spacer"
:
"/images/shared/spacer.gif"
]
for
(
name
,
path
)
in
imagePaths
{
(
"The path to '\(
name
)' is '\(
path
)'."
)
}
// Prints "The path to 'star' is '/glyphs/star.png'."
// Prints "The path to 'portrait' is '/images/content/portrait.jpg'."
// Prints "The path to 'spacer' is '/images/shared/spacer.gif'."
The order of key-value pairs in a dictionary is stable between mutations
but is otherwise unpredictable. If you need an ordered collection of
key-value pairs and don't need the fast key lookup that Dictionary
provides, see the KeyValuePairs
type for an alternative.
You can search a dictionary's contents for a particular value using the
contains(where:)
or firstIndex(where:)
methods supplied by default
implementation. The following example checks to see if imagePaths
contains
any paths in the "/glyphs"
directory:
let
glyphIndex
=
imagePaths
.
firstIndex
(
where
: { $
0
.
value
.
hasPrefix
(
"/glyphs"
) })
if
let
index
=
glyphIndex
{
(
"The '\(
imagePaths
[
index
].
key
)' image is a glyph."
)
}
else
{
(
"No glyphs found!"
)
}
// Prints "The 'star' image is a glyph.")
Note that in this example, imagePaths
is subscripted using a dictionary
index. Unlike the key-based subscript, the index-based subscript returns
the corresponding key-value pair as a non-optional tuple.
(
imagePaths
[
glyphIndex
!])
// Prints "("star", "/glyphs/star.png")"
A dictionary's indices stay valid across additions to the dictionary as long as the dictionary has enough capacity to store the added values without allocating more buffer. When a dictionary outgrows its buffer, existing indices may be invalidated without any notification.
When you know how many new values you're adding to a dictionary, use the
init(minimumCapacity:)
initializer to allocate the correct amount of
buffer.
Bridging Between Dictionary and NSDictionary
You can bridge between Dictionary
and NSDictionary
using the as
operator. For bridging to be possible, the Key
and Value
types of a
dictionary must be classes, @objc
protocols, or types that bridge to
Foundation types.
Bridging from Dictionary
to NSDictionary
always takes O(1) time and
space. When the dictionary's Key
and Value
types are neither classes
nor @objc
protocols, any required bridging of elements occurs at the
first access of each element. For this reason, the first operation that
uses the contents of the dictionary may take O(n).
Bridging from NSDictionary
to Dictionary
first calls the copy(with:)
method (- copyWithZone:
in Objective-C) on the dictionary to get an
immutable copy and then performs additional Swift bookkeeping work that
takes O(1) time. For instances of NSDictionary
that are already
immutable, copy(with:)
usually returns the same dictionary in O(1) time;
otherwise, the copying performance is unspecified. The instances of
NSDictionary
and Dictionary
share buffer using the same copy-on-write
optimization that is used when two instances of Dictionary
share
buffer.
Initializers
Creates a new dictionary from the key-value pairs in the given sequence, using a combining closure to determine the value for any duplicate keys.
You use this initializer to create a dictionary when you have a sequence
of key-value tuples that might have duplicate keys. As the dictionary is
built, the initializer calls the combine
closure with the current and
new values for any duplicate keys. Pass a closure as combine
that
returns the value to use in the resulting dictionary: The closure can
choose between the two values, combine them to produce a new value, or
even throw an error.
The following example shows how to choose the first and last values for any duplicate keys:
let
pairsWithDuplicateKeys
= [(
"a"
,
1
), (
"b"
,
2
), (
"a"
,
3
), (
"b"
,
4
)]
let
firstValues
=
Dictionary
(
pairsWithDuplicateKeys
,
uniquingKeysWith
: { (
first
,
_
)
in
first
})
// ["b": 2, "a": 1]
let
lastValues
=
Dictionary
(
pairsWithDuplicateKeys
,
uniquingKeysWith
: { (
_
,
last
)
in
last
})
// ["b": 4, "a": 3]
Declaration
@
inlinable
public
init
<
S
>
(
_
keysAndValues
:
S
,
uniquingKeysWith
combine
: (
Value
,
Value
)
throws
-
>
Value
)
rethrows
where
S
:
Sequence
,
S
.
Element
== (
Key
,
Value
)
Creates a dictionary initialized with a dictionary literal.
Do not call this initializer directly. It is called by the compiler to handle dictionary literals. To use a dictionary literal as the initial value of a dictionary, enclose a comma-separated list of key-value pairs in square brackets.
For example, the code sample below creates a dictionary with string keys and values.
let
countryCodes
= [
"BR"
:
"Brazil"
,
"GH"
:
"Ghana"
,
"JP"
:
"Japan"
]
(
countryCodes
)
// Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
- Parameter elements: The key-value pairs that will make up the new
dictionary. Each key in
elements
must be unique.
Declaration
@
inlinable
public
init
(
dictionaryLiteral
elements
: (
Key
,
Value
))
Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.
The arrays in the "values" position of the new dictionary each contain at least one element, with the elements in the same order as the source sequence.
The following example declares an array of names, and then creates a dictionary from that array by grouping the names by first letter:
let
students
= [
"Kofi"
,
"Abena"
,
"Efua"
,
"Kweku"
,
"Akosua"
]
let
studentsByLetter
=
Dictionary
(
grouping
:
students
,
by
: { $
0
.
first
! })
// ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]
The new studentsByLetter
dictionary has three entries, with students'
names grouped by the keys "E"
, "K"
, and "A"
.
Declaration
@
inlinable
public
init
<
S
>
(
grouping
values
:
S
,
by
keyForValue
: (
S
.
Element
)
throws
-
>
Key
)
rethrows
where
Value
== [
S
.
Element
],
S
:
Sequence
Creates an empty dictionary with preallocated space for at least the specified number of elements.
Use this initializer to avoid intermediate reallocations of a dictionary's storage buffer when you know how many key-value pairs you are adding to a dictionary after creation.
- Parameter minimumCapacity: The minimum number of key-value pairs that the newly created dictionary should be able to store without reallocating its storage buffer.
Declaration
public
init
(
minimumCapacity
:
Int
)
Creates a new dictionary from the key-value pairs in the given sequence.
You use this initializer to create a dictionary when you have a sequence
of key-value tuples with unique keys. Passing a sequence with duplicate
keys to this initializer results in a runtime error. If your
sequence might have duplicate keys, use the
Dictionary(_:uniquingKeysWith:)
initializer instead.
The following example creates a new dictionary using an array of strings as the keys and the integers in a countable range as the values:
let
digitWords
= [
"one"
,
"two"
,
"three"
,
"four"
,
"five"
]
let
wordToValue
=
Dictionary
(
uniqueKeysWithValues
:
zip
(
digitWords
,
1
...
5
))
(
wordToValue
[
"three"
]!)
// Prints "3"
(
wordToValue
)
// Prints "["three": 3, "four": 4, "five": 5, "one": 1, "two": 2]"
- Parameter keysAndValues: A sequence of key-value pairs to use for
the new dictionary. Every key in
keysAndValues
must be unique.
Precondition: The sequence must not have duplicate keys.
Declaration
@
inlinable
public
init
<
S
>
(
uniqueKeysWithValues
keysAndValues
:
S
)
where
S
:
Sequence
,
S
.
Element
== (
Key
,
Value
)
Instance Variables
The total number of key-value pairs that the dictionary can contain without allocating new storage.
Declaration
var
capacity
:
Int
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
A textual representation of this instance, suitable for debugging.
Calling this property directly is discouraged. Instead, convert an
instance of any type to a string by using the String(reflecting:)
initializer. This initializer works with any type, and uses the custom
debugDescription
property for types that conform to
CustomDebugStringConvertible
:
struct
Point
:
CustomDebugStringConvertible
{
let
x
:
Int
,
y
:
Int
var
debugDescription
:
String
{
return
"(\(
x
), \(
y
))"
}
}
let
p
=
Point
(
x
:
21
,
y
:
30
)
let
s
=
String
(
reflecting
:
p
)
(
s
)
// Prints "(21, 30)"
The conversion of p
to a string in the assignment to s
uses the
Point
type's debugDescription
property.
Declaration
var
debugDescription
:
String
A textual representation of this instance, suitable for debugging.
Calling this property directly is discouraged. Instead, convert an
instance of any type to a string by using the String(reflecting:)
initializer. This initializer works with any type, and uses the custom
debugDescription
property for types that conform to
CustomDebugStringConvertible
:
struct
Point
:
CustomDebugStringConvertible
{
let
x
:
Int
,
y
:
Int
var
debugDescription
:
String
{
return
"(\(
x
), \(
y
))"
}
}
let
p
=
Point
(
x
:
21
,
y
:
30
)
let
s
=
String
(
reflecting
:
p
)
(
s
)
// Prints "(21, 30)"
The conversion of p
to a string in the assignment to s
uses the
Point
type's debugDescription
property.
Declaration
var
debugDescription
:
String
A string that represents the contents of the dictionary, suitable for debugging.
Declaration
var
debugDescription
:
String
A textual representation of this instance.
Calling this property directly is discouraged. Instead, convert an
instance of any type to a string by using the String(describing:)
initializer. This initializer works with any type, and uses the custom
description
property for types that conform to
CustomStringConvertible
:
struct
Point
:
CustomStringConvertible
{
let
x
:
Int
,
y
:
Int
var
description
:
String
{
return
"(\(
x
), \(
y
))"
}
}
let
p
=
Point
(
x
:
21
,
y
:
30
)
let
s
=
String
(
describing
:
p
)
(
s
)
// Prints "(21, 30)"
The conversion of p
to a string in the assignment to s
uses the
Point
type's description
property.
Declaration
var
description
:
String
A textual representation of this instance.
Calling this property directly is discouraged. Instead, convert an
instance of any type to a string by using the String(describing:)
initializer. This initializer works with any type, and uses the custom
description
property for types that conform to
CustomStringConvertible
:
struct
Point
:
CustomStringConvertible
{
let
x
:
Int
,
y
:
Int
var
description
:
String
{
return
"(\(
x
), \(
y
))"
}
}
let
p
=
Point
(
x
:
21
,
y
:
30
)
let
s
=
String
(
describing
:
p
)
(
s
)
// Prints "(21, 30)"
The conversion of p
to a string in the assignment to s
uses the
Point
type's description
property.
Declaration
var
description
:
String
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
:
Dictionary
<
Key
,
Value
>
.
Index
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
:
Dictionary
<
Key
,
Value
>
.
Index
The dictionary's "past the end" position---that is, the position one greater than the last valid subscript argument.
If the collection is empty, endIndex
is equal to startIndex
.
Complexity: Amortized O(1) if the dictionary does not wrap a bridged
NSDictionary
; otherwise, the performance is unspecified.
Declaration
var
endIndex
:
Dictionary
<
Key
,
Value
>
.
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
?
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
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
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
A collection containing just the keys of the dictionary.
When iterated over, keys appear in this collection in the same order as they occur in the dictionary's key-value pairs. Each key in the keys collection has a unique value.
let
countryCodes
= [
"BR"
:
"Brazil"
,
"GH"
:
"Ghana"
,
"JP"
:
"Japan"
]
(
countryCodes
)
// Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
for
k
in
countryCodes
.
keys
{
(
k
)
}
// Prints "BR"
// Prints "JP"
// Prints "GH"
Declaration
var
keys
:
Dictionary
<
Key
,
Value
>
.
Keys
A sequence containing the same elements as this sequence,
but on which some operations, such as map
and filter
, are
implemented lazily.
Declaration
var
lazy
:
LazySequence
<
Self
>
The position of the first element in a nonempty collection.
If the collection is empty, startIndex
is equal to endIndex
.
Declaration
var
startIndex
:
Dictionary
<
Key
,
Value
>
.
Index
The position of the first element in a nonempty collection.
If the collection is empty, startIndex
is equal to endIndex
.
Declaration
var
startIndex
:
Dictionary
<
Key
,
Value
>
.
Index
The position of the first element in a nonempty dictionary.
If the collection is empty, startIndex
is equal to endIndex
.
Complexity: Amortized O(1) if the dictionary does not wrap a bridged
NSDictionary
. If the dictionary wraps a bridgedNSDictionary
, the performance is unspecified.
Declaration
var
startIndex
:
Dictionary
<
Key
,
Value
>
.
Index
A value less than or equal to the number of elements in the sequence, calculated nondestructively.
The default implementation returns 0. If you provide your own implementation, make sure to compute the value nondestructively.
Complexity: O(1), except if the sequence also conforms to
Collection
. In this case, see the documentation ofCollection.underestimatedCount
.
Declaration
var
underestimatedCount
:
Int
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
A collection containing just the values of the dictionary.
When iterated over, values appear in this collection in the same order as they occur in the dictionary's key-value pairs.
let
countryCodes
= [
"BR"
:
"Brazil"
,
"GH"
:
"Ghana"
,
"JP"
:
"Japan"
]
(
countryCodes
)
// Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
for
v
in
countryCodes
.
values
{
(
v
)
}
// Prints "Brazil"
// Prints "Japan"
// Prints "Ghana"
Declaration
var
values
:
Dictionary
<
Key
,
Value
>
.
Values
Subscripts
Accesses the value associated with the given key for reading and writing.
This key-based subscript returns the value for the given key if the key
is found in the dictionary, or nil
if the key is not found.
The following example creates a new dictionary and prints the value of a
key found in the dictionary ("Coral"
) and a key not found in the
dictionary ("Cerise"
).
var
hues
= [
"Heliotrope"
:
296
,
"Coral"
:
16
,
"Aquamarine"
:
156
]
(
hues
[
"Coral"
])
// Prints "Optional(16)"
(
hues
[
"Cerise"
])
// Prints "nil"
When you assign a value for a key and that key already exists, the dictionary overwrites the existing value. If the dictionary doesn't contain the key, the key and value are added as a new key-value pair.
Here, the value for the key "Coral"
is updated from 16
to 18
and a
new key-value pair is added for the key "Cerise"
.
hues
[
"Coral"
] =
18
(
hues
[
"Coral"
])
// Prints "Optional(18)"
hues
[
"Cerise"
] =
330
(
hues
[
"Cerise"
])
// Prints "Optional(330)"
If you assign nil
as the value for the given key, the dictionary
removes that key and its associated value.
In the following example, the key-value pair for the key "Aquamarine"
is removed from the dictionary by assigning nil
to the key-based
subscript.
hues
[
"Aquamarine"
] =
nil
(
hues
)
// Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]"
- Parameter key: The key to find in the dictionary.
Declaration
@
inlinable
public
subscript
(
key
:
Key
) -
>
Value
?
Accesses the value with the given key. If the dictionary doesn't contain the given key, accesses the provided default value as if the key and default value existed in the dictionary.
Use this subscript when you want either the value for a particular key or, when that key is not present in the dictionary, a default value. This example uses the subscript with a message to use in case an HTTP response code isn't recognized:
var
responseMessages
= [
200
:
"OK"
,
403
:
"Access forbidden"
,
404
:
"File not found"
,
500
:
"Internal server error"
]
let
httpResponseCodes
= [
200
,
403
,
301
]
for
code
in
httpResponseCodes
{
let
message
=
responseMessages
[
code
,
default
:
"Unknown response"
]
(
"Response \(
code
): \(
message
)"
)
}
// Prints "Response 200: OK"
// Prints "Response 403: Access Forbidden"
// Prints "Response 301: Unknown response"
When a dictionary's Value
type has value semantics, you can use this
subscript to perform in-place operations on values in the dictionary.
The following example uses this subscript while counting the occurrences
of each letter in a string:
When letterCounts[letter, defaultValue: 0] += 1
is executed with a
value of letter
that isn't already a key in letterCounts
, the
specified default value (0
) is returned from the subscript,
incremented, and then added to the dictionary under that key.
Note: Do not use this subscript to modify dictionary values if the dictionary's
Value
type is a class. In that case, the default value and key are not written back to the dictionary after an operation.
Declaration
@
inlinable
public
subscript
(
key
:
Key
,
default
defaultValue
: @
autoclosure
() -
>
Value
) -
>
Value
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
(
position
:
Dictionary
<
Key
,
Value
>
.
Index
) -
>
Dictionary
<
Key
,
Value
>
.
Keys
.
Element
Accesses the element at the specified position.
For example, you can replace an element of an array by using its subscript.
var
streets
= [
"Adams"
,
"Bryant"
,
"Channing"
,
"Douglas"
,
"Evarts"
]
streets
[
1
] =
"Butler"
(
streets
[
1
])
// Prints "Butler"
You can subscript a collection with any valid index other than the collection's end index. The end index refers to the position one past the last element of a collection, so it doesn't correspond with an element.
- Parameter position: The position of the element to access.
position
must be a valid index of the collection that is not equal to theendIndex
property.
Complexity: O(1)
Declaration
@
inlinable
public
subscript
(
position
:
Dictionary
<
Key
,
Value
>
.
Index
) -
>
Dictionary
<
Key
,
Value
>
.
Values
.
Element
Accesses the key-value pair at the specified position.
This subscript takes an index into the dictionary, instead of a key, and returns the corresponding key-value pair as a tuple. When performing collection-based operations that return an index into a dictionary, use this subscript with the resulting value.
For example, to find the key for a particular value in a dictionary, use
the firstIndex(where:)
method.
let
countryCodes
= [
"BR"
:
"Brazil"
,
"GH"
:
"Ghana"
,
"JP"
:
"Japan"
]
if
let
index
=
countryCodes
.
firstIndex
(
where
: { $
0
.
value
==
"Japan"
}) {
(
countryCodes
[
index
])
(
"Japan's country code is '\(
countryCodes
[
index
].
key
)'."
)
}
else
{
(
"Didn't find 'Japan' as a value in the dictionary."
)
}
// Prints "("JP", "Japan")"
// Prints "Japan's country code is 'JP'."
- Parameter position: The position of the key-value pair to access.
position
must be a valid index of the dictionary and not equal toendIndex
.
Declaration
@
inlinable
public
subscript
(
position
:
Dictionary
<
Key
,
Value
>
.
Index
) -
>
Dictionary
<
Key
,
Value
>
.
Element
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 a Boolean value indicating whether every element of a sequence satisfies a given predicate.
The following code uses this method to test whether all the names in an array have at least five characters:
let
names
= [
"Sofia"
,
"Camilla"
,
"Martina"
,
"Mateo"
,
"Nicolás"
]
let
allHaveAtLeastFive
=
names
.
allSatisfy
({ $
0
.
count
>
=
5
})
// allHaveAtLeastFive == true
- Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition.
Complexity: O(n), where n is the length of the sequence.
Declaration
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 non-optional values when your transformation produces an optional value.
In this example, note the difference in the result of using map
and
compactMap
with a transformation that returns an optional Int
value.
- Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.
Complexity: O(m + n), where n is the length of this sequence and m is the length of the result.
Declaration
@
inlinable
public
func
compactMap
<
ElementOfResult
>
(
_
transform
: (
Self
.
Element
)
throws
-
>
ElementOfResult
?)
rethrows
-
>
[
ElementOfResult
]
Returns a new dictionary containing only the key-value pairs that have
non-nil
values as the result of transformation by the given closure.
Use this method to receive a dictionary with non-optional values when your transformation produces optional values.
In this example, note the difference in the result of using mapValues
and compactMapValues
with a transformation that returns an optional
Int
value.
- Parameter transform: A closure that transforms a value.
transform
accepts each value of the dictionary as its parameter and returns an optional transformed value of the same or of a different type.
Complexity: O(m + n), where n is the length of the original dictionary and m is the length of the resulting dictionary.
Declaration
@
inlinable
public
func
compactMapValues
<
T
>
(
_
transform
: (
Value
)
throws
-
>
T
?)
rethrows
-
>
[
Key
:
T
]
Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
You can use the predicate to check for an element of a type that
doesn't conform to the Equatable
protocol, such as the
HTTPResponse
enumeration in this example.
enum
HTTPResponse
{
case
ok
case
error
(
Int
)
}
let
lastThreeResponses
: [
HTTPResponse
] = [.
ok
, .
ok
, .
error
(
404
)]
let
hadError
=
lastThreeResponses
.
contains
{
element
in
if
case
.
error
=
element
{
return
true
}
else
{
return
false
}
}
// 'hadError' == true
Alternatively, a predicate can be satisfied by a range of Equatable
elements or a general condition. This example shows how you can check an
array for an expense greater than $100.
let
expenses
= [
21.37
,
55.21
,
9.32
,
10.18
,
388.77
,
11.41
]
let
hasBigPurchase
=
expenses
.
contains
{ $
0
>
100
}
// 'hasBigPurchase' == true
- Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match.
Complexity: O(n), where n is the length of the sequence.
Declaration
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 sequence by skipping the initial, consecutive elements that satisfy the given predicate.
The following example uses the drop(while:)
method to skip over the
positive numbers at the beginning of the numbers
array. The result
begins with the first element of numbers
that does not satisfy
predicate
.
let
numbers
= [
3
,
7
,
4
, -
2
,
9
, -
6
,
10
,
1
]
let
startingWithNegative
=
numbers
.
drop
(
while
: { $
0
>
0
})
// startingWithNegative == [-2, 9, -6, 10, 1]
If predicate
matches every element in the sequence, the result is an
empty sequence.
- Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the result.
Complexity: O(k), where k is the number of elements to drop from the beginning of the sequence.
Declaration
@
inlinable
public
func
drop
(
while
predicate
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
DropWhileSequence
<
Self
>
Returns a 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 sequence containing all but the given number of initial elements.
If the number of elements to drop exceeds the number of elements in the sequence, the result is an empty sequence.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
dropFirst
(
2
))
// Prints "[3, 4, 5]"
(
numbers
.
dropFirst
(
10
))
// Prints "[]"
- Parameter k: The number of elements to drop from the beginning of
the sequence.
k
must be greater than or equal to zero.
Complexity: O(1), with O(k) deferred to each iteration of the result, where k is the number of elements to drop from the beginning of the sequence.
Declaration
@
inlinable
public
func
dropFirst
(
_
k
:
Int
=
1
) -
>
DropFirstSequence
<
Self
>
Returns a subsequence containing all but the 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 sequence containing all but the given number of final elements.
The sequence must be finite. If the number of elements to drop exceeds the number of elements in the sequence, the result is an empty sequence.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
dropLast
(
2
))
// Prints "[1, 2, 3]"
(
numbers
.
dropLast
(
10
))
// Prints "[]"
- Parameter n: The number of elements to drop off the end of the
sequence.
n
must be greater than or equal to zero.
Complexity: O(n), where n is the length of the sequence.
Declaration
@
inlinable
public
func
dropLast
(
_
k
:
Int
=
1
) -
>
[
Self
.
Element
]
Returns a 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 a Boolean value indicating whether this sequence and another sequence contain equivalent elements in the same order, using the given predicate as the equivalence test.
At least one of the sequences must be finite.
The predicate must be a equivalence relation over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
Complexity: O(m), where m is the lesser of the length of the sequence and the length of
other
.
Declaration
Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.
This example enumerates the characters of the string "Swift" and prints each character along with its place in the string.
for
(
n
,
c
)
in
"Swift"
.
enumerated
() {
(
"\(
n
): '\(
c
)'"
)
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"
When you enumerate a collection, the integer part of each pair is a counter
for the enumeration, but is not necessarily the index of the paired value.
These counters can be used as indices only in instances of zero-based,
integer-indexed collections, such as Array
and ContiguousArray
. For
other collections the counters may be out of range or of the wrong type
to use as an index. To iterate over the elements of a collection with its
indices, use the zip(_:_:)
function.
This example iterates over the indices and elements of a set, building a list consisting of indices of names with five or fewer letters.
Now that the shorterIndices
array holds the indices of the shorter
names in the names
set, you can use those indices to access elements in
the set.
for
i
in
shorterIndices
{
(
names
[
i
])
}
// Prints "Sofia"
// Prints "Mateo"
Complexity: O(1)
Declaration
@
inlinable
public
func
enumerated
() -
>
EnumeratedSequence
<
Self
>
Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
In this example, filter(_:)
is used to include only names shorter than
five characters.
let
cast
= [
"Vivien"
,
"Marlon"
,
"Kim"
,
"Karl"
]
let
shortNames
=
cast
.
filter
{ $
0
.
count
<
5
}
(
shortNames
)
// Prints "["Kim", "Karl"]"
- Parameter isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array.
Complexity: O(n), where n is the length of the sequence.
Declaration
@
inlinable
public
func
filter
(
_
isIncluded
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
[
Self
.
Element
]
Returns a new dictionary containing the key-value pairs of the dictionary that satisfy the given predicate.
- Parameter isIncluded: A closure that takes a key-value pair as its argument and returns a Boolean value indicating whether the pair should be included in the returned dictionary.
Declaration
@
available
(
swift
4.0
) @
inlinable
public
func
filter
(
_
isIncluded
: (
Dictionary
<
Key
,
Value
>
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
[
Key
:
Value
]
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."
- Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
Complexity: O(n), where n is the length of the sequence.
Declaration
@
inlinable
public
func
first
(
where
predicate
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
.
Element
?
Returns 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
?
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())
.
- Parameter transform: A closure that accepts an element of this sequence as its argument and returns a sequence or collection.
Complexity: O(m + n), where n is the length of this sequence and m is the length of the result.
Declaration
@
inlinable
public
func
flatMap
<
SegmentOfResult
>
(
_
transform
: (
Self
.
Element
)
throws
-
>
SegmentOfResult
)
rethrows
-
>
[
SegmentOfResult
.
Element
]
where
SegmentOfResult
:
Sequence
Declaration
@
available
(
swift
,
deprecated
:
4.1
,
renamed
:
"compactMap(_:)"
,
message
:
"Please use compactMap(_:) for the case where closure returns an optional value"
)
public
func
flatMap
<
ElementOfResult
>
(
_
transform
: (
Self
.
Element
)
throws
-
>
ElementOfResult
?)
rethrows
-
>
[
ElementOfResult
]
Calls the given closure on each element in the sequence in the same order
as a for
-in
loop.
The two loops in the following example produce the same output:
let
numberWords
= [
"one"
,
"two"
,
"three"
]
for
word
in
numberWords
{
(
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.
- Parameter body: A closure that takes an element of the sequence as a parameter.
Declaration
@
inlinable
public
func
forEach
(
_
body
: (
Self
.
Element
)
throws
-
>
Void
)
rethrows
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
Dictionary
<
Key
,
Value
>
.
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
Dictionary
<
Key
,
Value
>
.
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
)
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
Dictionary
<
Key
,
Value
>
.
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
:
Dictionary
<
Key
,
Value
>
.
Index
) -
>
Dictionary
<
Key
,
Value
>
.
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
:
Dictionary
<
Key
,
Value
>
.
Index
) -
>
Dictionary
<
Key
,
Value
>
.
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
:
Dictionary
<
Key
,
Value
>
.
Index
) -
>
Dictionary
<
Key
,
Value
>
.
Index
Returns the index for the given key.
If the given key is found in the dictionary, this method returns an index into the dictionary that corresponds with the key-value pair.
let
countryCodes
= [
"BR"
:
"Brazil"
,
"GH"
:
"Ghana"
,
"JP"
:
"Japan"
]
let
index
=
countryCodes
.
index
(
forKey
:
"JP"
)
(
"Country code for \(
countryCodes
[
index
!].
value
): '\(
countryCodes
[
index
!].
key
)'."
)
// Prints "Country code for Japan: 'JP'."
- Parameter key: The key to find in the dictionary.
Declaration
@
inlinable
public
func
index
(
forKey
key
:
Key
) -
>
Dictionary
<
Key
,
Value
>
.
Index
?
Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.
The predicate must be a strict weak ordering over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
Note: This method implements the mathematical notion of lexicographical ordering, which has no connection to Unicode. If you are sorting strings to present to the end user, use
String
APIs that perform localized comparison instead.
Complexity: O(m), where m is the lesser of the length of the sequence and the length of
other
.
Declaration
Returns an iterator over the dictionary's key-value pairs.
Iterating over a dictionary yields the key-value pairs as two-element
tuples. You can decompose the tuple in a for
-in
loop, which calls
makeIterator()
behind the scenes, or when calling the iterator's
next()
method directly.
let
hues
= [
"Heliotrope"
:
296
,
"Coral"
:
16
,
"Aquamarine"
:
156
]
for
(
name
,
hueValue
)
in
hues
{
(
"The hue of \(
name
) is \(
hueValue
)."
)
}
// Prints "The hue of Heliotrope is 296."
// Prints "The hue of Coral is 16."
// Prints "The hue of Aquamarine is 156."
Declaration
@
inlinable
public
func
makeIterator
() -
>
Dictionary
<
Key
,
Value
>
.
Iterator
Returns an array containing the results of mapping the given closure over the sequence's elements.
In this example, map
is used first to convert the names in the array
to lowercase strings and then to count their characters.
let
cast
= [
"Vivien"
,
"Marlon"
,
"Kim"
,
"Karl"
]
let
lowercaseNames
=
cast
.
map
{ $
0
.
lowercased
() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let
letterCounts
=
cast
.
map
{ $
0
.
count
}
// 'letterCounts' == [6, 6, 3, 4]
- Parameter transform: A mapping closure.
transform
accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type.
Complexity: O(n), where n is the length of the sequence.
Declaration
@
inlinable
public
func
map
<
T
>
(
_
transform
: (
Self
.
Element
)
throws
-
>
T
)
rethrows
-
>
[
T
]
Returns 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 new dictionary containing the keys of this dictionary with the values transformed by the given closure.
- Parameter transform: A closure that transforms a value.
transform
accepts each value of the dictionary as its parameter and returns a transformed value of the same or of a different type.
Complexity: O(n), where n is the length of the dictionary.
Declaration
@
inlinable
public
func
mapValues
<
T
>
(
_
transform
: (
Value
)
throws
-
>
T
)
rethrows
-
>
[
Key
:
T
]
Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
The predicate must be a strict weak ordering over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
This example shows how to use the max(by:)
method on a
dictionary to find the 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))"
- Parameter areInIncreasingOrder: A predicate that returns
true
if its first argument should be ordered before its second argument; otherwise,false
.
Complexity: O(n), where n is the length of the sequence.
Declaration
@
warn_unqualified_access
@
inlinable
public
func
max
(
by
areInIncreasingOrder
: (
Self
.
Element
,
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
.
Element
?
Merges the key-value pairs in the given sequence into the dictionary, using a combining closure to determine the value for any duplicate keys.
Use the combine
closure to select a value to use in the updated
dictionary, or to combine existing and new values. As the key-value
pairs are merged with the dictionary, the combine
closure is called
with the current and new values for any duplicate keys that are
encountered.
This example shows how to choose the current or new values for any duplicate keys:
var
dictionary
= [
"a"
:
1
,
"b"
:
2
]
// Keeping existing value for key "a":
dictionary
.
merge
(
zip
([
"a"
,
"c"
], [
3
,
4
])) { (
current
,
_
)
in
current
}
// ["b": 2, "a": 1, "c": 4]
// Taking the new value for key "a":
dictionary
.
merge
(
zip
([
"a"
,
"d"
], [
5
,
6
])) { (
_
,
new
)
in
new
}
// ["b": 2, "a": 5, "c": 4, "d": 6]
Declaration
@
inlinable
public
mutating
func
merge
<
S
>
(
_
other
:
S
,
uniquingKeysWith
combine
: (
Value
,
Value
)
throws
-
>
Value
)
rethrows
where
S
:
Sequence
,
S
.
Element
== (
Key
,
Value
)
Merges the given dictionary into this dictionary, using a combining closure to determine the value for any duplicate keys.
Use the combine
closure to select a value to use in the updated
dictionary, or to combine existing and new values. As the key-values
pairs in other
are merged with this dictionary, the combine
closure
is called with the current and new values for any duplicate keys that
are encountered.
This example shows how to choose the current or new values for any duplicate keys:
var
dictionary
= [
"a"
:
1
,
"b"
:
2
]
// Keeping existing value for key "a":
dictionary
.
merge
([
"a"
:
3
,
"c"
:
4
]) { (
current
,
_
)
in
current
}
// ["b": 2, "a": 1, "c": 4]
// Taking the new value for key "a":
dictionary
.
merge
([
"a"
:
5
,
"d"
:
6
]) { (
_
,
new
)
in
new
}
// ["b": 2, "a": 5, "c": 4, "d": 6]
Declaration
@
inlinable
public
mutating
func
merge
(
_
other
: [
Key
:
Value
],
uniquingKeysWith
combine
: (
Value
,
Value
)
throws
-
>
Value
)
rethrows
Creates a dictionary by merging key-value pairs in a sequence into the dictionary, using a combining closure to determine the value for duplicate keys.
Use the combine
closure to select a value to use in the returned
dictionary, or to combine existing and new values. As the key-value
pairs are merged with the dictionary, the combine
closure is called
with the current and new values for any duplicate keys that are
encountered.
This example shows how to choose the current or new values for any duplicate keys:
let
dictionary
= [
"a"
:
1
,
"b"
:
2
]
let
newKeyValues
=
zip
([
"a"
,
"b"
], [
3
,
4
])
let
keepingCurrent
=
dictionary
.
merging
(
newKeyValues
) { (
current
,
_
)
in
current
}
// ["b": 2, "a": 1]
let
replacingCurrent
=
dictionary
.
merging
(
newKeyValues
) { (
_
,
new
)
in
new
}
// ["b": 4, "a": 3]
Declaration
@
inlinable
public
func
merging
<
S
>
(
_
other
:
S
,
uniquingKeysWith
combine
: (
Value
,
Value
)
throws
-
>
Value
)
rethrows
-
>
[
Key
:
Value
]
where
S
:
Sequence
,
S
.
Element
== (
Key
,
Value
)
Creates a dictionary by merging the given dictionary into this dictionary, using a combining closure to determine the value for duplicate keys.
Use the combine
closure to select a value to use in the returned
dictionary, or to combine existing and new values. As the key-value
pairs in other
are merged with this dictionary, the combine
closure
is called with the current and new values for any duplicate keys that
are encountered.
This example shows how to choose the current or new values for any duplicate keys:
let
dictionary
= [
"a"
:
1
,
"b"
:
2
]
let
otherDictionary
= [
"a"
:
3
,
"b"
:
4
]
let
keepingCurrent
=
dictionary
.
merging
(
otherDictionary
)
{ (
current
,
_
)
in
current
}
// ["b": 2, "a": 1]
let
replacingCurrent
=
dictionary
.
merging
(
otherDictionary
)
{ (
_
,
new
)
in
new
}
// ["b": 4, "a": 3]
Declaration
@
inlinable
public
func
merging
(
_
other
: [
Key
:
Value
],
uniquingKeysWith
combine
: (
Value
,
Value
)
throws
-
>
Value
)
rethrows
-
>
[
Key
:
Value
]
Returns the minimum element in the sequence, using the given predicate as the comparison between elements.
The predicate must be a strict weak ordering over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
This example shows how to use the min(by:)
method on a
dictionary to find the 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))"
- Parameter areInIncreasingOrder: A predicate that returns
true
if its first argument should be ordered before its second argument; otherwise,false
.
Complexity: O(n), where n is the length of the sequence.
Declaration
@
warn_unqualified_access
@
inlinable
public
func
min
(
by
areInIncreasingOrder
: (
Self
.
Element
,
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
.
Element
?
Removes and returns the first key-value pair of the dictionary if the dictionary isn't empty.
The first element of the dictionary is not necessarily the first element added. Don't expect any particular ordering of key-value pairs.
Complexity: Averages to O(1) over many calls to
popFirst()
.
Declaration
@
inlinable
public
mutating
func
popFirst
() -
>
Dictionary
<
Key
,
Value
>
.
Element
?
Returns a sequence, up to the specified maximum length, containing the initial elements of the sequence.
If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
prefix
(
2
))
// Prints "[1, 2]"
(
numbers
.
prefix
(
10
))
// Prints "[1, 2, 3, 4, 5]"
- Parameter maxLength: The maximum number of elements to return. The
value of
maxLength
must be greater than or equal to zero.
Complexity: O(1)
Declaration
@
inlinable
public
func
prefix
(
_
maxLength
:
Int
) -
>
PrefixSequence
<
Self
>
Returns a 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 sequence containing the initial, consecutive elements that satisfy the given predicate.
The following example uses the prefix(while:)
method to find the
positive numbers at the beginning of the numbers
array. Every element
of numbers
up to, but not including, the first negative value is
included in the result.
let
numbers
= [
3
,
7
,
4
, -
2
,
9
, -
6
,
10
,
1
]
let
positivePrefix
=
numbers
.
prefix
(
while
: { $
0
>
0
})
// positivePrefix == [3, 7, 4]
If predicate
matches every element in the sequence, the resulting
sequence contains every element of the sequence.
- Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the result.
Complexity: O(k), where k is the length of the result.
Declaration
@
inlinable
public
func
prefix
(
while
predicate
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
[
Self
.
Element
]
Returns 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 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(_:_:)
.
Complexity: O(n), where n is the length of the sequence.
Declaration
Returns the result of combining the elements of the sequence using the given closure.
Use the reduce(into:_:)
method to produce a single value from the
elements of an entire sequence. For example, you can use this method on an
array of integers to filter adjacent equal entries or count frequencies.
This method is preferred over reduce(_:_:)
for efficiency when the
result is a copy-on-write type, for example an Array or a Dictionary.
The updateAccumulatingResult
closure is called sequentially with a
mutable accumulating value initialized to initialResult
and each element
of the sequence. This example shows how to build a dictionary of letter
frequencies of a string.
let
letters
=
"abracadabra"
let
letterCount
=
letters
.
reduce
(
into
: [:]) {
counts
,
letter
in
counts
[
letter
,
default
:
0
] +=
1
}
// letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]
When letters.reduce(into:_:)
is called, the following steps occur:
- The
updateAccumulatingResult
closure is called with the initial accumulating value---[:]
in this case---and the first character ofletters
, modifying the accumulating value by setting1
for the key"a"
. - The closure is called again repeatedly with the updated accumulating value and each element of the sequence.
- When the sequence is exhausted, the accumulating value is returned to the caller.
If the sequence has no elements, updateAccumulatingResult
is never
executed and initialResult
is the result of the call to
reduce(into:_:)
.
Complexity: O(n), where n is the length of the sequence.
Declaration
Removes and returns the key-value pair at the specified index.
Calling this method invalidates any existing indices for use with this dictionary.
- Parameter index: The position of the key-value pair to remove.
index
must be a valid index of the dictionary, and must not equal the dictionary's end index.
Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Declaration
@
inlinable
public
mutating
func
remove
(
at
index
:
Dictionary
<
Key
,
Value
>
.
Index
) -
>
Dictionary
<
Key
,
Value
>
.
Element
Removes all key-value pairs from the dictionary.
Calling this method invalidates all indices with respect to the dictionary.
- Parameter keepCapacity: Whether the dictionary should keep its
underlying buffer. If you pass
true
, the operation preserves the buffer capacity that the collection has, otherwise the underlying buffer is released. The default isfalse
.
Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Declaration
@
inlinable
public
mutating
func
removeAll
(
keepingCapacity
keepCapacity
:
Bool
=
false
)
Removes the given key and its associated value from the dictionary.
If the key is found in the dictionary, this method returns the key's associated value. On removal, this method invalidates all indices with respect to the dictionary.
var
hues
= [
"Heliotrope"
:
296
,
"Coral"
:
16
,
"Aquamarine"
:
156
]
if
let
value
=
hues
.
removeValue
(
forKey
:
"Coral"
) {
(
"The value \(
value
) was removed."
)
}
// Prints "The value 16 was removed."
If the key isn't found in the dictionary, removeValue(forKey:)
returns
nil
.
if
let
value
=
hues
.
removeValueForKey
(
"Cerise"
) {
(
"The value \(
value
) was removed."
)
}
else
{
(
"No value found for that key."
)
}
// Prints "No value found for that key.""
- Parameter key: The key to remove along with its associated value.
Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Declaration
@
inlinable
public
mutating
func
removeValue
(
forKey
key
:
Key
) -
>
Value
?
Reserves enough space to store the specified number of key-value pairs.
If you are adding a known number of key-value pairs to a dictionary, use this method to avoid multiple reallocations. This method ensures that the dictionary has unique, mutable, contiguous storage, with space allocated for at least the requested number of key-value pairs.
Calling the reserveCapacity(_:)
method on a dictionary with bridged
storage triggers a copy to contiguous storage even if the existing
storage has room to store minimumCapacity
key-value pairs.
- Parameter minimumCapacity: The requested number of key-value pairs to store.
Declaration
public
mutating
func
reserveCapacity
(
_
minimumCapacity
:
Int
)
Returns an array containing the elements of this sequence in reverse order.
The sequence must be finite.
Complexity: O(n), where n is the length of the sequence.
Declaration
@
inlinable
public
func
reversed
() -
>
[
Self
.
Element
]
Returns the elements of the sequence, shuffled.
For example, you can shuffle the numbers between 0
and 9
by calling
the shuffled()
method on that range:
let
numbers
=
0
...
9
let
shuffledNumbers
=
numbers
.
shuffled
()
// shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0]
This method is equivalent to calling shuffled(using:)
, passing in the
system's default random generator.
Complexity: O(n), where n is the length of the sequence.
Declaration
@
inlinable
public
func
shuffled
() -
>
[
Self
.
Element
]
Returns the elements of the sequence, shuffled using the given generator as a source for randomness.
You use this method to randomize the elements of a sequence when you are
using a custom random number generator. For example, you can shuffle the
numbers between 0
and 9
by calling the shuffled(using:)
method on
that range:
let
numbers
=
0
...
9
let
shuffledNumbers
=
numbers
.
shuffled
(
using
:
&
myGenerator
)
// shuffledNumbers == [8, 9, 4, 3, 2, 6, 7, 0, 5, 1]
- Parameter generator: The random number generator to use when shuffling the sequence.
Complexity: O(n), where n is the length of the sequence.
Note: The algorithm used to shuffle a sequence may change in a future version of Swift. If you're passing a generator that results in the same shuffled order each time you run your program, that sequence may change when your program is compiled using a different version of Swift.
Declaration
@
inlinable
public
func
shuffled
<
T
>
(
using
generator
:
inout
T
) -
>
[
Self
.
Element
]
where
T
:
RandomNumberGenerator
Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.
When you want to sort a sequence of elements that don't conform to the
Comparable
protocol, pass a predicate to this method that returns
true
when the first element should be ordered before the second. The
elements of the resulting array are ordered according to the given
predicate.
In the following example, the predicate provides an ordering for an array
of a custom HTTPResponse
type. The predicate orders errors before
successes and sorts the error responses by their error code.
enum
HTTPResponse
{
case
ok
case
error
(
Int
)
}
let
responses
: [
HTTPResponse
] = [.
error
(
500
), .
ok
, .
ok
, .
error
(
404
), .
error
(
403
)]
let
sortedResponses
=
responses
.
sorted
{
switch
($
0
, $
1
) {
// Order errors by code
case
let
(.
error
(
aCode
), .
error
(
bCode
)):
return
aCode
<
bCode
// All successes are equivalent, so none is before any other
case
(.
ok
, .
ok
):
return
false
// Order errors before successes
case
(.
error
, .
ok
):
return
true
case
(.
ok
, .
error
):
return
false
}
}
(
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"]"
The predicate must be a strict weak ordering over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
The sorting algorithm is not guaranteed to be stable. A stable sort
preserves the relative order of elements for which
areInIncreasingOrder
does not establish an order.
- Parameter areInIncreasingOrder: A predicate that returns
true
if its first argument should be ordered before its second argument; otherwise,false
.
Complexity: O(n log n), where n is the length of the sequence.
Declaration
@
inlinable
public
func
sorted
(
by
areInIncreasingOrder
: (
Self
.
Element
,
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
[
Self
.
Element
]
Returns the longest possible subsequences of the sequence, in order, that don't contain elements satisfying the given predicate. Elements that are used to split the sequence are not returned as part of any subsequence.
The following examples show the effects of the maxSplits
and
omittingEmptySubsequences
parameters when splitting a string using a
closure that matches spaces. The first use of split
returns each word
that was originally separated by one or more spaces.
let
line
=
"BLANCHE: I don't want realism. I want magic!"
(
line
.
split
(
whereSeparator
: { $
0
==
" "
})
.
map
(
String
.
init
))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
The second example passes 1
for the maxSplits
parameter, so the
original string is split just once, into two new strings.
(
line
.
split
(
maxSplits
:
1
,
whereSeparator
: { $
0
==
" "
})
.
map
(
String
.
init
))
// Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
The final example passes true
for the allowEmptySlices
parameter, so
the returned array contains empty strings where spaces were repeated.
(
line
.
split
(
omittingEmptySubsequences
:
false
,
whereSeparator
: { $
0
==
" "
}
).
map
(
String
.
init
))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
Complexity: O(n), where n is the length of the sequence.
Declaration
@
inlinable
public
func
split
(
maxSplits
:
Int
=
Int
.
max
,
omittingEmptySubsequences
:
Bool
=
true
,
whereSeparator
isSeparator
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
[
ArraySlice
<
Self
.
Element
>
]
Returns 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 Boolean value indicating whether the initial elements of the sequence are equivalent to the elements in another sequence, using the given predicate as the equivalence test.
The predicate must be a equivalence relation over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
Complexity: O(m), where m is the lesser of the length of the sequence and the length of
possiblePrefix
.
Declaration
Returns a subsequence, up to the given maximum length, containing the final elements of the sequence.
The sequence must be finite. If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
suffix
(
2
))
// Prints "[4, 5]"
(
numbers
.
suffix
(
10
))
// Prints "[1, 2, 3, 4, 5]"
- Parameter maxLength: The maximum number of elements to return. The
value of
maxLength
must be greater than or equal to zero.
Complexity: O(n), where n is the length of the sequence.
Declaration
@
inlinable
public
func
suffix
(
_
maxLength
:
Int
) -
>
[
Self
.
Element
]
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
Exchanges the values at the specified indices of the collection.
Both parameters must be valid indices of the collection and not
equal to endIndex
. Passing the same index as both i
and j
has no
effect.
Complexity: O(1)
Declaration
@
inlinable
public
mutating
func
swapAt
(
_
i
:
Dictionary
<
Key
,
Value
>
.
Index
,
_
j
:
Dictionary
<
Key
,
Value
>
.
Index
)
Updates the value stored in the dictionary for the given key, or adds a new key-value pair if the key does not exist.
Use this method instead of key-based subscripting when you need to know
whether the new value supplants the value of an existing key. If the
value of an existing key is updated, updateValue(_:forKey:)
returns
the original value.
var
hues
= [
"Heliotrope"
:
296
,
"Coral"
:
16
,
"Aquamarine"
:
156
]
if
let
oldValue
=
hues
.
updateValue
(
18
,
forKey
:
"Coral"
) {
(
"The old value of \(
oldValue
) was replaced with a new one."
)
}
// Prints "The old value of 16 was replaced with a new one."
If the given key is not present in the dictionary, this method adds the
key-value pair and returns nil
.
if
let
oldValue
=
hues
.
updateValue
(
330
,
forKey
:
"Cerise"
) {
(
"The old value of \(
oldValue
) was replaced with a new one."
)
}
else
{
(
"No value was found in the dictionary for that key."
)
}
// Prints "No value was found in the dictionary for that key."
Declaration
@
inlinable
public
mutating
func
updateValue
(
_
value
:
Value
,
forKey
key
:
Key
) -
>
Value
?
Call body(p)
, where p
is a pointer to the collection's
contiguous storage. If no such storage exists, it is
first created. If the collection does not support an internal
representation in a form of contiguous storage, body
is not
called and nil
is returned.
A Collection
that provides its own implementation of this method
must also guarantee that an equivalent buffer of its SubSequence
can be generated by advancing the pointer by the distance to the
slice's startIndex
.
Declaration
@
inlinable
public
func
withContiguousStorageIfAvailable
<
R
>
(
_
body
: (
UnsafeBufferPointer
<
Self
.
Element
>
)
throws
-
>
R
)
rethrows
-
>
R
?
Type Methods
Returns a Boolean value indicating whether two values are equal.
Equality is the inverse of inequality. For any values a
and b
,
a == b
implies that a != b
is false
.
Declaration
@
inlinable
public
static
func
==(
lhs
:
Dictionary
<
Key
,
Value
>
.
Keys
,
rhs
:
Dictionary
<
Key
,
Value
>
.
Keys
) -
>
Bool
This associated type appears as a requirement in the
Sequence
protocol, but it is restated here with stricter constraints. In a collection, the subsequence should also conform toCollection
.