Swift dictionary set

Source: Internet
Author: User

Swift dictionary set

A 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.

Shows the "student ID and student" set in the dictionary structure. Student IDs are key sets and cannot be repeated. Students are Value Sets and can be repeated.

 


The prompt shows that the set of keys and values in the dictionary is unordered. Even if the keys or values are added in order, the keys or values are unordered. Dictionary sets are more suitable for quick value access through keys. Just like an English dictionary, keys are the English words to be queried, while values are the translation and interpretation of English words. Sometimes, an English word corresponds to multiple translations and explanations, which also corresponds to the dictionary set feature.

I. dictionary declaration and initialization

Swift provides the Dictionary struct type for the Dictionary. We can use the following statement when declaring a Dictionary.

Var studentDictionary: Dictionary <Int, String>

The studentDictionary variable explicitly specifies the type as Dictionary <Int, String>. <Int, String> indicates that the set of keys is of the Int type and the set of values is of the String type.

In fact, the set declared above is not available and needs to be initialized. The set type is often initialized while declared. The sample code is as follows:

Var studentDictionary1: Dictionary <Int, String> = [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"] ③ var studentDictionary4 = Dictionary <Int, String> () ④

The above Code declares and initializes the dictionary. Code ① ~ ③ Use [102: "Zhang San", 105: "Li Si", 109:
The "Wang Wu"] method is initialized. This is a dictionary representation, as shown in the syntax.

 


This syntax is similar to an object in JSON. The dictionary starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each key is followed by a colon (:), and key-value pairs are separated by commas.

Row ③ is the let declaration dictionary. The dictionary declared by the let statement is an unchangeable dictionary and must be initialized at the same time. Once initialized, the dictionary cannot be modified.

Line 4 of the Code initializes an empty dictionary. The key set is of the Int type, and the value set is of the String type. After initialization, there is no element.

Ii. dictionary Modification

We can append, delete, and replace the elements in the dictionary. The append of dictionary elements is relatively simple. If a valid value is assigned to a nonexistent key, a "key-value" pair is appended.

There are two ways to delete a dictionary element. One is to assign a value to nil to a key to delete the element. The other is to delete the element through the removeValueForKey method of the dictionary, the method return value is the value to be deleted.

There are two ways to replace dictionary elements. One is to directly assign values to an existing key, so that the new value replaces the old value; another method is to replace the value with the updateValue (forKey :) method. The return value of the method is the value to be replaced.

Here is an example:

Var studentDictionary = [102: "Zhang San", 105: "Li Si", 109: "Wang Wu"] ① studentDictionary [110] = "Dong Liu" ② println ("Class Number: \ (studentDictionary. count) ") ③ let dismissStudent = studentDictionary. removeValueForKey (102) ④ println ("expelled student: \ (dismissStudent)") ⑤ studentDictionary [105] = nil ⑥ studentDictionary [109] = "James" 7let replaceStudent = studentDictionary. updateValue ("Li Si", forKey: 110) Student println ("replaced Student: \ (replaceStudent)") Student

The output result is as follows:

Class count: 4

Expelled student: James

The replaced student is Dong 6.

The first line of the above Code declares and initializes the dictionary studentDictionary. The second line of code append an element with a key of 110 and a value of "Dong Liu, the Code in line ③ prints the number of students in the class. count is the attribute of the dictionary and returns the length of the dictionary.

Lines ④ and ⑥ both delete elements. Line ④ uses the removeValueForKey method to delete elements. dismissStudent is the return value, which maintains the deleted elements. Therefore, the output of dismissStudent in Row 5 is "expelled student: James ". The row 6 studentDictionary [105] = nil statement is directly assigned a value to nil. You can also delete the elements corresponding to 105.

Line 7 and line 7 both replace the old element. If the key of Line 7 does not exist, a new key-value pair is appended to the dictionary. The Nth row replaces the element by using the updateValue (forKey :) method. The return value of the method is "Dong 6", and the nth row of code prints "The replaced student is Dong 6 ".

3. dictionary Traversal

A dictionary traversal set is also an important operation of a dictionary. Different from arrays, the dictionary has two sets. Therefore, the traversal process can only traverse the set of values, only the set of keys, or both. 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"] println ("--- traversal key ---") for studentID in studentDictionary. keys {① println ("student ID: \ (studentID)")} println ("--- traversal value ---") for studentName in studentDictionary. values {② println ("Student: \ (studentName)")} println ("--- traversal key: Value ---") for (studentID, studentName) in studentDictionary {③ println ("\ (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

From the code above, we can see that we have three methods to traverse the dictionary, all of which use the for in statement. The Code in line ① traverses the key set, where keys is the dictionary attribute and can return the set of all keys. The Code in line ② traverses the set of values, where values is a dictionary attribute and can return a set of all values. The row ③ code traverses the retrieved dictionary elements. (studentID, studentName) is a tuples, which are composed of the key variable studentID and the value variable studentName.


For more information, please refer to the first domestic Swift book "Swift development guide" for discussion. Website: http://www.51work6.com/swift.phpwelcome to the swifttechnology discussion group: 362298.pdf

Welcome to Zhijie iOS public classroom Platform



An answer to an idiom dictionary

Answer
Silent response

C # Generic set and dictionary set. Example tutorial

List <int> list = new List <int> ();
List. add (1 );
List. add (2 );
List. add (3 );
Foreach (int I in list)
{
// I is the value in the list.
}

Dictionary <int, int> dic = new Dictionary <int, int> ();
Dic. add (1, 1 );
Dic. add (2, 2 );
Dic. add (1, 3.3 );
Traverse dictionary
Foreach (int I in dic. keys)
{
... // I is the dictionary KEY.
Int m = dic [I]; // value
}
Foreach (int j in dic. values)
{
... // J is the valuse of the dictionary
}

// Generate a dictionary using list
Dictionary <int, int> dic = new Dictionary <int, int> ();
Foreach (int m in list) // The top one in list
{
If (! Dic. containkeys (m ))
Dic. add (m, m );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.