-
Notifications
You must be signed in to change notification settings - Fork 0
/
Review - Dictionaries
41 lines (28 loc) · 1.48 KB
/
Review - Dictionaries
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
A dictionary is an unordered collection of key-value pairs.
A key is a unique identifier used to create, update, remove, or access an associated value.
We can create populated dictionaries using dictionary literals:
var dictionaryName = [Key1: Value1, Key2: Value2]
An empty dictionary contains no key-values pairs. There are two methods of initializing an empty dictionary:
// Initializer Syntax:
var emptyInitializer = [KeyType: ValueType]()
// Dictionary Literal Syntax:
var emptyLiteral: [KeyType: ValueType] = [:]
We can add elements to a dictionary using subscript syntax:
dictionaryName[NewKey] = NewValue
We can remove dictionary elements using .removeValue() or by setting a key value to nil.
dictionaryName.removeValue(forKey: Key)
dictionaryName[Key] = nil
We can remove all the values from a dictionary with .removeAll().
We can update the value of a key-value pair using subscript syntax or .updateValue():
dictionaryName[Key] = NewValue
dictionaryName.updateValue(NewValue, forKey: Key)
The .isEmpty property returns a boolean that equals true if a dictionary is empty.
The .count property returns the number of elements contained within a dictionary.
We can access a value using its key:
dictionaryName[Key]
We can use for-in loops to iterate through the content of a dictionary:
for (KeyHolder, ValueHolder) in dictionaryName {
// Add body
}
We can use the .keys property to access only the keys of a dictionary.
We can use the .values property to access only the values of a dictionary.