Definition of a dictionary
Similar to the array mentioned in the previous article, a dictionary is also a data structure used to hold elements of the same data type. However, the dictionary is a key to find a specific value (value), and each data item (item) stored in the dictionary is a key-value pair.
Hashiha
Each value of a key-value pair has no special requirements, but only variables of the type that can be hashed can be used as keys to key-value pairs. It can be Hashiha that a variable of that type must provide a way to calculate its own hash value. A variable with a different hash value is not necessarily the same, and vice versa.
When judging a = = B, in fact, it will be converted to A.hashvalue = = B.hashvalue. All underlying types in Swift (String,int,double,bool, and so on) are types that can be hashed, and enumeration member values that have no associated values can also be hashed. The custom type satisfies the protocol hashable and can also be hashed.
Create a dictionary
Analogous to the creation of arrays, there are two types of dictionaries. This is not explained in detail, and the reader who does not understand can read the section on the creation of the array in the previous article. Give the code directly:
var dictionary1: Dictionary <String, Int> = ["key1": 1]
var dictionary2: [String: Int] = ["key2": 2, "key3": 3]
println ("dictionary1 = \ (dictionary1)")
println ("dictionary2 = \ (dictionary2)")
Dictionary addition, deletion, modification and modification
For the calculation of the length of the complete analog array, the length of the dictionary can also be obtained through the count property of the dictionary.
var dictionary1: Dictionary <String, Int> = ["key1": 1]
println ("dictionary1 = \ (dictionary1.count)")
Determine dictionary is empty
Similarly, you can use the isEmpty attribute of the dictionary to determine whether the dictionary is empty.
var dictionary1: Dictionary <String, Int> = ["key1": 1]
if! dictionary1.isEmpty {
println ("Dictionary is not empty")
}
Add dictionary elements
Unlike the append method of the array call, the dictionary can increase the length through the syntax of the attached script. The specific usage method is: dictionaryName [newKey] = newValue. Examples are as follows:
var dictionary1: Dictionary <String, Int> = ["key1": 1]
dictionary1 ["key2"] = 2
println ("dictionary1 = \ (dictionary1)")
Output result:
dictionary1 = [key1: 1, key2: 2]
Unlike arrays, dictionary elements cannot be added through dictionary slicing.
Access dictionary elements
The data stored in the dictionary can only be obtained by key. The method is relatively simple:
var dictionary1: Dictionary <String, Int> = ["key1": 1]
var value = dictionary1 ["key1"] // get value
println ("value = \ (value!)")
dictionary1 ["key1"] = 2 // modify value
println ("dictionary1 = \ (dictionary1)")
operation result:
value = 1
dictionary1 = [key1: 2]
It should be noted that since the value corresponding to the key does not necessarily exist, the value obtained using the syntax of the attached script is an optional type. It needs to be used after being unsealed. The specific use method can be found in chapter four. Here, in order to save (tou) space (lan), I used the wrong, or rather rigorous unsealing method.
In addition, you can see that through the attached script, you can not only get the values in the dictionary, but also modify them directly. Of course, similar to the array, you can also use the updateValue (forKey :) method to modify the value in the dictionary.
var dictionary1: Dictionary <String, Int> = ["key1": 1]
dictionary1.updateValue (2, forKey: "key1")
dictionary1.updateValue (2, forKey: "key2")
println ("dictionary1 = \ (dictionary1)")
It doesn't matter if the key doesn't exist, Swift will automatically create a new key-value pair for us.
Delete dictionary elements
The elements in the dictionary can also be deleted using affiliate scripts. Just set the value to nil, but the value parameter in the updateValue (forKey :) method cannot be nil.
var dictionary1: Dictionary <String, Int> = ["key1": 1]
dictionary1.updateValue (2, forKey: "key2")
println ("dictionary1 = \ (dictionary1)")
dictionary1 ["key2"] = nil
//dictionary1.updateValue(nil, forKey: "key1") // Syntax error, parameter cannot be nil
println ("dictionary1 = \ (dictionary1)")
operation result:
dictionary1 = [key1: 1, key2: 2]
dictionary1 = [key1: 1]
The removeAll method can remove all data in the dictionary.
var dictionary1: Dictionary <String, Int> = ["key1": 1]
dictionary1.removeAll (keepCapacity: true)
// There is also the simplest way to write
dictionary1 = [:]
Regardless of whether keepCapacity is true, dictionary1 after this line of code is executed, isEmpty = true, count = 0
keepCapacity: If true, is a non-binding request to avoid releasing storage, which can be a useful optimization when x is going to be grown again.
If keepCapacity is set to true, then the space allocated to the dictionary will not be released, if the dictionary will add content again, this is a performance optimization. But even so, the count attribute of the dictionary is still 0.
There is another way to delete the dictionary, which is to use the removeAtIndex method. The parameter should be an object of type DictionaryIndex, and an optional type needs to be obtained through the indexForKey method, and then unsealed. Note that if the value in the optional type is nil, you cannot call the removeAtIndex method! Otherwise it will cause a runtime error. In order to save (lan) space (lan), the code for mandatory type unsealing is not given here.
var dictionary1: Dictionary <String, Int> = ["key1": 1]
dictionary1.removeAtIndex (dictionary1.indexForKey ("key1")!)
println ("dictionary1 = \ (dictionary1)")
This method is not recommended because it is cumbersome and difficult.
Traverse the dictionary
The dictionary can be traversed through a for in loop, not only the key-value pairs of the dictionary, but also the keys or values of the dictionary.
var dictionary1: Dictionary <String, Int> = ["key1": 1, "key2": 2]
for (keyName, valueName) in dictionary1 {
println ("keyName = \ (keyName) valueName = \ (valueName)")
}
If you want to access the keys individually, just change dictionary1 after in to dictionary1.keys.
Dictionary initialization
The initialization method of the dictionary is similar to the array, but it can only be initialized using standard syntax. The dictionary has no special constructor.
// Either way can create an empty dictionary
var dic1 = [String, Int] ()
var dic2 = Dictionary <String, Int> ()
to sum up
Because the dictionary is unordered, the overall operation is simpler than the array. Compared with the NSDictionary in OC, the dictionary in Swift is easier to modify and the syntax is simple, but there will be more trivial details, unlike the OC that can be used in a few kinds of syntax.
Regardless of whether the reader has already understood the array in Swift when reading this article, it is recommended to combine the array and the dictionary to learn and compare their similarities and differences.
Appendix View the complete column-"Swift Easy Start"
[Introduction to Swift (1)-Basic Grammar]
[Introduction to Swift (2)-Characters and Strings]
[Introduction to Swift (3)-Tuple]
[Introduction to Swift (4)-Optionals and Asserts]
[Introduction to Swift (5)-Array]
[Introduction to Swift (6)-Dictionary]
Copyright statement: This article is an original article by bloggers and may not be reproduced without the permission of the bloggers.
Introduction to Swift (6)-Dictionary