In Swift, dictionary types are used to store key and value pairs. Similar to Map in Java
Declaration and initialization
The syntax of the declaration dictionary is: var dictionary_name [param1:param2]
Represents a dictionary type in which param1 is the key type param2 is a value type, such as:
1
var dic1:[Int:String]
Generic are also available to use:
1
var dic2:Dictionary<Int,String>
This way has the same effect as [:]
When you create a dictionary, you can also not display the type of the declaration dictionary, and you can make the compiler automatically infer by assigning an initial value
1
var dic3 = ["1":"one"]
It is also possible to declare and then assign values, such as dic1 and dic2 declared above
var dic4:[Int:Int] = [:] var dic5:Dictionary<Int,Int> = Dictionary()
Determine the number of elements
Use the count property
1
dic1.count
Determine if the dictionary is empty
Use the isEmpty property
1 2 3
if dic4.isEmpty{ print("Dictionary is empty.") }
Basic access operations
Get the value by key
1
print(dic1[1])
In order to avoid the absence of a key in the dictionary and result in the value being empty, we can also use the if let method we have in the optional type, as follows:
1 2 3
if let value = dic2[1] { print("The Value is \(value)") }
Modify value
1
dic1[1]="0"
Append a item
1
dic1[4] = "4"
Dictionaries are out of order, and key is not necessarily an integer
Use updateValue to update the value
1
dic1.updateValue("1", forKey: 1)
The method looks the same as the result of a direct assignment, but the method actually has a return value, so that you can get the original value at the same time as the update, such as:
1 2 3
iflet oldValue = dic1.updateValue("One", forKey: 1) { print("Old Value is \(oldValue)") }
Delete Item
Delete item by key
1
dic1.removeValue(forKey: 1)
Delete all items
1
dic1.removeAll()
Iterate item
Iterate item by key
1 2 3
for item in dic2.keys { print(item) }
Iterate item by value
1 2 3
for item in dic2.values { print(item) }
Iterate directly through the dictionary
1 2 3
for item in dic2 { print(item) }
Or
1 2 3
for (key,value) in dic2 { print("\(key):\(value)") }