The Swift dictionary represents a very complex collection that allows elements to be accessed by a key. A dictionary is a set of two parts, one is a set of key (key), and the other is a collection of values (value). A key collection cannot have duplicate elements, and a collection of values can be duplicated, and the keys and values are paired.
Dictionary Declaration and initialization
The Swift dictionary type is Dictionary and is also a generic collection.
you can use one of the following statements when declaring a dictionary type.
[HTML]View PlainCopyprint?
- var studentdictionary1:dictionary<Int, String>
- var studentDictionary2: [Int:string]
The dictionary of the Declaration needs to be initialized to be used, and the dictionary type is often initialized at the same time as the declaration. The sample code is as follows:
[HTML]View PlainCopyprint?
- var studentdictionary1:dictionary<Int, String>
- ê= [102: "Zhang San", 105: "John Doe", 109: "Harry"]
- var studentDictionary2 = [102: "Zhang San", 105: "John Doe", 109: "Harry"]
- Let studentDictionary3 = [102: "Zhang San", 105: "John Doe", 109: "Harry"]
Dictionary traversal
The dictionary traversal process can traverse only the collection of values, or only the collection of keys, or it can traverse at the same time. These traversal processes are implemented through the for-in loop.
The following is a sample code that iterates through a dictionary:
[HTML]View PlainCopyprint?
- var studentdictionary = [102: "Zhang San", 105: "John Doe", 109: "Harry"]
- Print ("---traversal key---")
- For StudentID in Studentdictionary.keys {
- Print ("School Number: \ (StudentID)")
- }
- Print ("---traversal value---")
- For Studentname in Studentdictionary.values {
- Print ("Student: \ (studentname)")
- }
- Print ("---traversal key: Value---")
- For (StudentID, studentname) in Studentdictionary {
- Print ("\ (StudentID): \ (studentname)")
- }
The results of the operation are as follows:
---traversal key ---
Study No.:
School Number:102
School Number:109
---traversal value ---
Student: John Doe
Student: Zhang San
Student: Harry
---traversal key : value ---
105: John Doe
102: Zhang San
109: Harry
Swift Dictionary Collection-standby