Swift 2.0 learning notes (Day 16)-dictionary set
The Swift dictionary represents a very complex set that allows elements to be accessed by a key. A dictionary consists of two parts: a key set and a value set. A key set cannot contain duplicate elements, while a value set can be duplicated. Keys and values are paired.
Dictionary declaration and initialization
The Swift Dictionary type is a Dictionary and a generic set.
When declaring a Dictionary type, you can use one of the following statements.
var studentDictionary1: Dictionary
var studentDictionary2: [Int: String]
The declared dictionary must be initialized before it can be used. The dictionary type is usually initialized at the same time. The sample code is as follows:
Var studentDictionary1: Dictionary
Latency = [102: Zhang San, 105: Li Si, 109: Wang Wu] var studentDictionary2 = [102: Zhang San, 105: Li Si, 109: Wang Wu] let studentDictionary3 = [102: Zhang San, 105: Li Si, 109: Wang Wu]
Dictionary Traversal
The dictionary traversal process can only traverse the set of values, only the set of keys, or simultaneously. These traversal processes are implemented through the for-in loop.
The following is a sample code for dictionary traversal:
Var studentDictionary = [102: Zhang San, 105: Li Si, 109: Wang Wu] print (--- traversal key ---) for studentID in studentDictionary. keys {print (student ID :( 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 running result is as follows:
--- Traversal key ---
Student ID: 105
Student ID: 102
Student ID: 109
--- Traversal value ---
Student: Li Si
Student: James
Student: Wang Wu
--- Traversal key: Value ---
105: Li Si
102: James
109: Wang Wu