In Swift Language Tutorial for Beginner 6 - Array, we’ve seen the use of list types in Swift, and now let’s look at dictionary types in Swift - Dictionary。
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
1 | dic1 = [1:"1",2:"2",3:"3"] |
You can also create an empty dictionary
1 | var dic4:[Int:Int] = [:] |
Determine the number of elements
Use the count property
1 | dic1.count |
Determine if the dictionary is empty
Use the isEmpty property
1 | if dic4.isEmpty{ |
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 | if let value = dic2[1] { |
- 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 | if let oldValue = dic1.updateValue("One", forKey: 1) { |
Delete Item
- Delete item by key
1 | dic1.removeValue(forKey: 1) |
- Delete all items
1 | dic1.removeAll() |
Iterate item
- Iterate item by key
1 | for item in dic2.keys { |
- Iterate item by value
1 | for item in dic2.values { |
- Iterate directly through the dictionary
1 | for item in dic2 { |
Or
1 | for (key,value) in dic2 { |
Next
Next, we’ll take a brief look at Set types in Swift. Swift Language Tutorial for Beginner 8 - Set