struct
Dictionary
<
Key
:
Hashable
,
Value
>
Inheritance |
Collection, CustomDebugStringConvertible, CustomReflectable, CustomStringConvertible, ExpressibleByDictionaryLiteral, Indexable, IndexableBase, Sequence
View Protocol Hierarchy →
|
---|---|
Associated Types |
The element type of a dictionary: a tuple containing an individual key-value pair.
The index type of a dictionary.
Type alias inferred.
Type alias inferred. |
Import |
|
Initializers
Creates an empty dictionary.
Declaration
init
()
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"]"
elements
: The key-value pairs that will make up the new
dictionary. Each key in elements
must be unique.
See Also: ExpressibleByDictionaryLiteral
Declaration
init
(
dictionaryLiteral
elements
: (
Key
,
Value
)...)
Creates a dictionary with at least the given number of elements worth of storage.
Use this initializer to avoid intermediate reallocations when you know
how many key-value pairs you are adding to a dictionary. The actual
capacity of the created dictionary is the smallest power of 2 that
is greater than or equal to minimumCapacity
.
minimumCapacity
: The minimum number of key-value pairs to
allocate storage for in the new dictionary.
Declaration
init
(
minimumCapacity
:
Int
)
Instance Variables
The number of key-value pairs in the dictionary.
Complexity: O(1).
Declaration
var
count
:
Int
{
get
}
A string that represents the contents of the dictionary, suitable for debugging.
Declaration
var
debugDescription
:
String
{
get
}
A string that represents the contents of the dictionary.
Declaration
var
description
:
String
{
get
}
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
:
DictionaryIndex
<
Key
,
Value
>
{
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
: (
key
:
Key
,
value
:
Value
)? {
get
}
Declared In
Collection
A Boolean value that indicates whether the dictionary is empty. (read only)
Dictionaries are empty when created with an initializer or an empty dictionary literal.
Declaration
var
isEmpty
:
Bool
{
get
}
Declared In
Dictionary
, Collection
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"
]
for
k
in
countryCodes
.
keys
{
(
k
)
}
// Prints "BR"
// Prints "JP"
// Prints "GH"
Declaration
var
keys
:
LazyMapCollection
<
[
Key
:
Value
],
Key
>
{
get
}
A view onto this collection that provides lazy implementations of
normally eager operations, such as map
and filter
.
Use the lazy
property when chaining operations to prevent
intermediate operations from allocating storage, or when you only
need a part of the final collection to avoid unnecessary computation.
See Also: LazySequenceProtocol
, LazyCollectionProtocol
.
Declaration
var
lazy
:
LazyCollection
<
Dictionary
<
Key
,
Value
>
>
{
get
}
Declared In
Collection
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 bridged NSDictionary
, the
performance is unspecified.
Declaration
var
startIndex
:
DictionaryIndex
<
Key
,
Value
>
{
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
Collection
, Sequence
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
:
LazyMapCollection
<
[
Key
:
Value
],
Value
>
{
get
}
3 inherited items hidden. (Show all)
Subscripts
Declaration
subscript
(
key
:
_Hashable
) -
>
Value
?
Accesses a contiguous subrange of the collection's elements.
The accessed slice uses the same indices for the same elements as the
original collection. Always use the slice's startIndex
property
instead of assuming that its indices start at a particular value.
This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array.
let
streets
= [
"Adams"
,
"Bryant"
,
"Channing"
,
"Douglas"
,
"Evarts"
]
let
streetsSlice
=
streets
[
2
..
<
streets
.
endIndex
]
(
streetsSlice
)
// Prints "["Channing", "Douglas", "Evarts"]"
let
index
=
streetsSlice
.
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
:
ClosedRange
<
DictionaryIndex
<
Key
,
Value
>
>
) -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
{
get
}
Declared In
Collection
, Indexable
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 index(where:)
method.
let
countryCodes
= [
"BR"
:
"Brazil"
,
"GH"
:
"Ghana"
,
"JP"
:
"Japan"
]
if
let
index
=
countryCodes
.
index
(
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'."
position
: The position of the key-value pair to access.
position
must be a valid index of the dictionary and not equal to
endIndex
.
Returns: A two-element tuple with the key and value corresponding to
position
.
Declaration
subscript
(
position
:
DictionaryIndex
<
Key
,
Value
>
) -
>
(
key
:
Key
,
value
:
Value
) {
get
}
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]"
key
: The key to find in the dictionary.
Returns: The value associated with key
if key
is in the dictionary;
otherwise, nil
.
Declaration
subscript
(
key
:
Key
) -
>
Value
?
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
<
DictionaryIndex
<
Key
,
Value
>
>
) -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
{
get
}
Declared In
Collection
2 inherited items hidden. (Show all)
Instance Methods
Declaration
func
!=(
lhs
: [
Key
:
Value
],
rhs
: [
Key
:
Value
]) -
>
Bool
Declaration
func
==(
lhs
: [
Key
:
Value
],
rhs
: [
Key
:
Value
]) -
>
Bool
Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
You can use the predicate to check for an element of a type that
doesn't conform to the Equatable
protocol, such as the
HTTPResponse
enumeration in this example.
enum
HTTPResponse
{
case
ok
case
error
(
Int
)
}
let
lastThreeResponses
: [
HTTPResponse
] = [.
ok
, .
ok
, .
error
(
404
)]
let
hadError
=
lastThreeResponses
.
contains
{
element
in
if
case
.
error
=
element
{
return
true
}
else
{
return
false
}
}
// 'hadError' == true
Alternatively, a predicate can be satisfied by a range of Equatable
elements or a general condition. This example shows how you can check an
array for an expense greater than $100.
let
expenses
= [
21.37
,
55.21
,
9.32
,
10.18
,
388.77
,
11.41
]
let
hasBigPurchase
=
expenses
.
contains
{ $
0
>
100
}
// 'hasBigPurchase' == true
predicate
: A closure that takes an element of the sequence
as its argument and returns a Boolean value that indicates whether
the passed element represents a match.
Returns: true
if the sequence contains an element that satisfies
predicate
; otherwise, false
.
Declaration
Declared In
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
:
DictionaryIndex
<
Key
,
Value
>
,
to
end
:
DictionaryIndex
<
Key
,
Value
>
) -
>
DictionaryIndex
<
Key
,
Value
>
Distance
Declared In
Collection
, Indexable
Returns a subsequence containing all but the first element of the sequence.
The following example drops the first element from an array of integers.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
dropFirst
())
// Prints "[2, 3, 4, 5]"
If the sequence has no elements, the result is an empty subsequence.
let
empty
: [
Int
] = []
(
empty
.
dropFirst
())
// Prints "[]"
Returns: A subsequence starting after the first element of the sequence.
Complexity: O(1)
Declaration
func
dropFirst
() -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
Declared In
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
) -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
Declared In
Collection
, Sequence
Returns a subsequence containing all but the last element of the sequence.
The sequence must be finite. If the sequence has no elements, the result is an empty subsequence.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
dropLast
())
// Prints "[1, 2, 3, 4]"
If the sequence has no elements, the result is an empty subsequence.
let
empty
: [
Int
] = []
(
empty
.
dropLast
())
// Prints "[]"
Returns: A subsequence leaving off the last element of the sequence.
Complexity: O(n), where n is the length of the sequence.
Declaration
func
dropLast
() -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
Declared In
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 the specified number of elements
at the end.
Complexity: O(n), where n is the length of the collection.
Declaration
func
dropLast
(
_
n
:
Int
) -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
Declared In
Collection
, Sequence
Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements, using the given predicate as the equivalence test.
At least one of the sequences must be finite.
The predicate must be a equivalence relation over the elements. That
is, for any elements a
, b
, and c
, the following conditions must
hold:
areEquivalent(a, a)
is alwaystrue
. (Reflexivity)areEquivalent(a, b)
impliesareEquivalent(b, a)
. (Symmetry)- If
areEquivalent(a, b)
andareEquivalent(b, c)
are bothtrue
, thenareEquivalent(a, c)
is alsotrue
. (Transitivity)
Parameters:
other: A sequence to compare to this sequence.
areEquivalent: A predicate that returns true
if its two arguments
are equivalent; otherwise, false
.
Returns: true
if this sequence and other
contain equivalent items,
using areEquivalent
as the equivalence test; otherwise, false.
See Also: elementsEqual(_:)
Declaration
Declared In
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
<
Dictionary
<
Key
,
Value
>
>
Declared In
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"]"
shouldInclude
: A closure that takes an element of the
sequence as its argument and returns a Boolean value indicating
whether the element should be included in the returned array.
Returns: An array of the elements that includeElement
allowed.
Declaration
func
filter
(
_
isIncluded
: ((
key
:
Key
,
value
:
Value
))
throws
-
>
Bool
)
rethrows
-
>
[(
key
:
Key
,
value
:
Value
)]
Declared In
Collection
, Sequence
Returns the first element of the sequence that satisfies the given predicate or nil if no such element is found.
predicate
: A closure that takes an element of the
sequence as its argument and returns a Boolean value indicating
whether the element is a match.
Returns: The first match or nil
if there was no match.
Declaration
func
first
(
where
predicate
: ((
key
:
Key
,
value
:
Value
))
throws
-
>
Bool
)
rethrows
-
>
(
key
:
Key
,
value
:
Value
)?
Declared In
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
: ((
key
:
Key
,
value
:
Value
))
throws
-
>
ElementOfResult
?)
rethrows
-
>
[
ElementOfResult
]
Declared In
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
:
Sequence
>
(
_
transform
: ((
key
:
Key
,
value
:
Value
))
throws
-
>
SegmentOfResult
)
rethrows
-
>
[
SegmentOfResult
.
Iterator
.
Element
]
Declared In
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
: ((
key
:
Key
,
value
:
Value
))
throws
-
>
Swift
.
Void
)
rethrows
Declared In
Collection
, Sequence
Offsets the given index by the specified distance.
The value passed as n
must not offset i
beyond the endIndex
or
before the startIndex
of this 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.
See Also: index(_:offsetBy:)
, formIndex(_:offsetBy:limitedBy:)
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
func
formIndex
(
_
i
:
inout
DictionaryIndex
<
Key
,
Value
>
,
offsetBy
n
:
DictionaryIndex
<
Key
,
Value
>
Distance
)
Declared In
Collection
, Indexable
Offsets the given index by the specified distance, or so that it equals the given limiting index.
The value passed as n
must not offset i
beyond the endIndex
or
before the startIndex
of this collection, unless the index passed as
limit
prevents offsetting beyond those bounds.
Parameters:
i: A valid index of the collection.
n: The distance to offset i
. n
must not be negative unless the
collection conforms to the BidirectionalCollection
protocol.
Returns: true
if i
has been offset by exactly n
steps without
going beyond limit
; otherwise, false
. When the return value is
false
, the value of i
is equal to limit
.
See Also: index(_:offsetBy:)
, formIndex(_:offsetBy:limitedBy:)
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
func
formIndex
(
_
i
:
inout
DictionaryIndex
<
Key
,
Value
>
,
offsetBy
n
:
DictionaryIndex
<
Key
,
Value
>
Distance
,
limitedBy
limit
:
DictionaryIndex
<
Key
,
Value
>
) -
>
Bool
Declared In
Collection
, Indexable
Replaces the given index with its successor.
i
: A valid index of the collection. i
must be less than
endIndex
.
Declaration
func
formIndex
(
after
i
:
inout
DictionaryIndex
<
Key
,
Value
>
)
Declared In
Collection
, Indexable
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 endIndex
or
before the startIndex
of this 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
:
DictionaryIndex
<
Key
,
Value
>
,
offsetBy
n
:
DictionaryIndex
<
Key
,
Value
>
Distance
) -
>
DictionaryIndex
<
Key
,
Value
>
Declared In
Collection
, Indexable
Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.
The following example obtains an index advanced four positions from a
string's starting index and then prints the character at that position.
The operation doesn't require going beyond the limiting s.endIndex
value, so it succeeds.
let
s
=
"Swift"
if
let
i
=
s
.
index
(
s
.
startIndex
,
offsetBy
:
4
,
limitedBy
:
s
.
endIndex
) {
(
s
[
i
])
}
// Prints "t"
The next example attempts to retrieve an index six positions from
s.startIndex
but fails, because that distance is beyond the index
passed as limit
.
let
j
=
s
.
index
(
s
.
startIndex
,
offsetBy
:
6
,
limitedBy
:
s
.
endIndex
)
(
j
)
// Prints "nil"
The value passed as n
must not offset i
beyond the endIndex
or
before the startIndex
of this collection, unless the index passed as
limit
prevents offsetting beyond those bounds.
Parameters:
i: A valid index of the collection.
n: The distance to offset i
. n
must not be negative unless the
collection conforms to the BidirectionalCollection
protocol.
limit: A valid index of the collection to use as a limit. If n > 0
,
a limit that is less than i
has no effect. Likewise, if n < 0
, a
limit that is greater than i
has no effect.
Returns: An index offset by n
from the index i
, unless that index
would be beyond limit
in the direction of movement. In that case,
the method returns nil
.
See Also: index(_:offsetBy:)
, formIndex(_:offsetBy:limitedBy:)
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(n), where n is the absolute
value of n
.
Declaration
func
index
(
_
i
:
DictionaryIndex
<
Key
,
Value
>
,
offsetBy
n
:
DictionaryIndex
<
Key
,
Value
>
Distance
,
limitedBy
limit
:
DictionaryIndex
<
Key
,
Value
>
) -
>
DictionaryIndex
<
Key
,
Value
>
?
Declared In
Collection
, Indexable
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
:
DictionaryIndex
<
Key
,
Value
>
) -
>
DictionaryIndex
<
Key
,
Value
>
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'."
key
: The key to find in the dictionary.
Returns: The index for key
and its associated value if key
is in
the dictionary; otherwise, nil
.
Declaration
func
index
(
forKey
key
:
Key
) -
>
DictionaryIndex
<
Key
,
Value
>
?
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
: ((
key
:
Key
,
value
:
Value
))
throws
-
>
Bool
)
rethrows
-
>
DictionaryIndex
<
Key
,
Value
>
?
Declared In
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
Declared In
Collection
, Sequence
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."
Returns: An iterator over the dictionary with elements of type
(key: Key, value: Value)
.
Declaration
func
makeIterator
() -
>
DictionaryIterator
<
Key
,
Value
>
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
: ((
key
:
Key
,
value
:
Value
))
throws
-
>
T
)
rethrows
-
>
[
T
]
Declared In
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
: ((
key
:
Key
,
value
:
Value
), (
key
:
Key
,
value
:
Value
))
throws
-
>
Bool
)
rethrows
-
>
(
key
:
Key
,
value
:
Value
)?
Declared In
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
@
warn_unqualified_access
func
min
(
by
areInIncreasingOrder
: ((
key
:
Key
,
value
:
Value
), (
key
:
Key
,
value
:
Value
))
throws
-
>
Bool
)
rethrows
-
>
(
key
:
Key
,
value
:
Value
)?
Declared In
Collection
, Sequence
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.
Returns: The first key-value pair of the dictionary if the dictionary
is not empty; otherwise, nil
.
Complexity: Averages to O(1) over many calls to popFirst()
.
Declaration
mutating
func
popFirst
() -
>
(
key
:
Key
,
value
:
Value
)?
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
) -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
Declared In
Collection
, Sequence
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
:
DictionaryIndex
<
Key
,
Value
>
) -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
Declared In
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
:
DictionaryIndex
<
Key
,
Value
>
) -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
Declared In
Collection
Returns the result of calling the given combining closure with each element of this sequence and an accumulating value.
The nextPartialResult
closure is called sequentially with an
accumulating value initialized to initialResult
and each
element of the sequence. This example shows how to find the sum
of an array of numbers.
When numbers.reduce(_:_:)
is called, the
following steps occur:
- The
nextPartialResult
closure is called with the initial result and the first element ofnumbers
, returning the sum:1
. - The closure is called again repeatedly with the previous call's return value and each element of the sequence.
- When the sequence is exhausted, the last value returned from the closure is returned to the caller.
Parameters:
initialResult: the initial accumulating value.
nextPartialResult: A closure that combines an accumulating
value and an element of the sequence into a new accumulating
value, to be used in the next call of the
nextPartialResult
closure or returned to the caller.
Returns: The final accumulated value.
Declaration
func
reduce
<
Result
>
(
_
initialResult
:
Result
,
_
nextPartialResult
: (
Result
, (
key
:
Key
,
value
:
Value
))
throws
-
>
Result
)
rethrows
-
>
Result
Declared In
Collection
, Sequence
Removes and returns the key-value pair at the specified index.
Calling this method invalidates any existing indices for use with this dictionary.
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.
Returns: The key-value pair that correspond to index
.
Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Declaration
mutating
func
remove
(
at
index
:
DictionaryIndex
<
Key
,
Value
>
) -
>
(
key
:
Key
,
value
:
Value
)
Removes all key-value pairs from the dictionary.
Calling this method invalidates all indices with respect to the dictionary.
keepCapacity
: Whether the dictionary should keep its
underlying storage. If you pass true
, the operation preserves the
storage capacity that the collection has, otherwise the underlying
storage is released. The default is false
.
Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Declaration
mutating
func
removeAll
(
keepingCapacity
keepCapacity
:
Bool
=
default
)
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.""
key
: The key to remove along with its associated value.
Returns: The value that was removed, or nil
if the key was not
present in the dictionary.
Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Declaration
mutating
func
removeValue
(
forKey
key
:
Key
) -
>
Value
?
Declaration
mutating
func
removeValue
<
ConcreteKey
:
Hashable
>
(
forKey
key
:
ConcreteKey
) -
>
Value
?
Returns an array containing the elements of this sequence in reverse order.
The sequence must be finite.
Complexity: O(n), where n is the length of the sequence.
Returns: An array containing the elements of this sequence in reverse order.
Declaration
func
reversed
() -
>
[(
key
:
Key
,
value
:
Value
)]
Declared In
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
: ((
key
:
Key
,
value
:
Value
), (
key
:
Key
,
value
:
Value
)) -
>
Bool
) -
>
[(
key
:
Key
,
value
:
Value
)]
Declared In
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
: ((
key
:
Key
,
value
:
Value
))
throws
-
>
Bool
)
rethrows
-
>
[
Slice
<
Dictionary
<
Key
,
Value
>
>
]
Declared In
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
Declared In
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 all the elements in the collection.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
suffix
(
2
))
// Prints "[4, 5]"
(
numbers
.
suffix
(
10
))
// Prints "[1, 2, 3, 4, 5]"
maxLength
: The maximum number of elements to return. The
value of maxLength
must be greater than or equal to zero.
Returns: A subsequence terminating at the end of the collection with at
most maxLength
elements.
Complexity: O(n), where n is the length of the collection.
Declaration
func
suffix
(
_
maxLength
:
Int
) -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
Declared In
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
:
DictionaryIndex
<
Key
,
Value
>
) -
>
Slice
<
Dictionary
<
Key
,
Value
>
>
Declared In
Collection
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."
Parameters:
value: The new value to add to the dictionary.
key: The key to associate with value
. If key
already exists in
the dictionary, value
replaces the existing associated value. If
key
isn't already a key of the dictionary, the (key, value)
pair
is added.
Returns: The value that was replaced, or nil
if a new key-value pair
was added.
Declaration
mutating
func
updateValue
(
_
value
:
Value
,
forKey
key
:
Key
) -
>
Value
?
Declaration
mutating
func
updateValue
<
ConcreteKey
:
Hashable
>
(
_
value
:
Value
,
forKey
key
:
ConcreteKey
) -
>
Value
?
33 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 Indices == DefaultIndices
The indices that are valid for subscripting the collection, in ascending order.
A collection's indices
property can hold a strong reference to the
collection itself, causing the collection to be non-uniquely referenced.
If you mutate the collection while iterating over its indices, a strong
reference can cause an unexpected copy of the collection. To avoid the
unexpected copy, use the index(after:)
method starting with
startIndex
to produce indices instead.
var
c
=
MyFancyCollection
([
10
,
20
,
30
,
40
,
50
])
var
i
=
c
.
startIndex
while
i
!=
c
.
endIndex
{
c
[
i
] /=
5
i
=
c
.
index
(
after
:
i
)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])
Declaration
var
indices
:
DefaultIndices
<
Dictionary
<
Key
,
Value
>
>
{
get
}
Declared In
Collection
1 inherited item hidden. (Show all)
A collection whose elements are key-value pairs.
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:
The
responseMessages
variable is inferred to have type[Int: String]
. TheKey
type of the dictionary isInt
, and theValue
type of the dictionary isString
.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'sKey
type, including all of Swift's basic types. You can use your own custom types as dictionary keys by making them conform to theHashable
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:
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.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.
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 the404
code to be simply "Not found" and removes the key-value pair for the500
code entirely.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 calledinterestingNumbers
with string keys and values that are integer arrays, then sorts each array in-place in descending order.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.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 theDictionaryLiteral
type for an alternative.You can search a dictionary's contents for a particular value using the
contains(where:)
orindex(where:)
methods supplied by default implementation. The following example checks to see ifimagePaths
contains any paths in the"/glyphs"
directory: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.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 storage. When a dictionary outgrows its storage, 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 storage.Bridging Between Dictionary and NSDictionary
You can bridge between
Dictionary
andNSDictionary
using theas
operator. For bridging to be possible, theKey
andValue
types of a dictionary must be classes,@objc
protocols, or types that bridge to Foundation types.Bridging from
Dictionary
toNSDictionary
always takes O(1) time and space. When the dictionary'sKey
andValue
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
toDictionary
first calls thecopy(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 ofNSDictionary
that are already immutable,copy(with:)
usually returns the same dictionary in O(1) time; otherwise, the copying performance is unspecified. The instances ofNSDictionary
andDictionary
share storage using the same copy-on-write optimization that is used when two instances ofDictionary
share storage.See Also:
Hashable