Swift Dictionary Collection

Source: Internet
Author: User



A dictionary represents a very complex collection that allows the element 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.



As shown in the dictionary structure of the "school number and students" collection, the number is a key set, can not be repeated, the student is a collection of values, it is possible to repeat.









Hints the collection of keys and values in the dictionary is unordered, even when added in order, and when the keys or values are taken out, they become unordered. The dictionary collection is more suitable for fast access to the value by key, like the English Dictionary, the key is to check the English words, and the value is English words translation and interpretation. Sometimes, an English word will correspond to multiple translations and interpretations, which correspond to the characteristics of the dictionary collection.



First, the dictionary Declaration and Initialization



Swift provides the dictionary struct type for the dictionary, and we can use the following statement when declaring a dictionary.



var studentdictionary:dictionary<int, string>



Where the variable studentdictionary explicitly specifies the type dictionary<int, string>. Where <int, string> is generic, which indicates that the collection of keys is of type Int and that the collection of values is of type String.



The set declared above is actually not available and needs to be initialized, and the collection type is often initialized at the same time as the declaration. The sample code is as follows:





[HTML]View Plaincopy


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







The above code is to declare and initialize the dictionary, the Code ①~③ line uses [102: "Zhang San", 105: "John Doe", 109:
"Harry"] is initialized in a way that is the way the dictionary is represented, as shown in the syntax.









This syntax is similar to the object in JSON, where the dictionary starts with "{" (opening parenthesis) and ends with "}" (the closing parenthesis). Each key is followed by a ":" (colon) and a "," (comma)-separated key-value pair.



The ③ line is a let declaration dictionary, which is the immutable dictionary, which must be initialized at the same time as the declaration and cannot be modified once initialized.



The code ④ line is initialized with an empty dictionary, the key collection is of type int, the value collection is string, and there is no element after initialization.



Ii. Modification of the dictionary



We can modify the elements in the dictionary by appending, deleting, and replacing them. The addition of a dictionary element is simple, as long as a valid value is assigned to a non-existent key, a "key-value" pair element is appended.



There are two ways to delete a dictionary element, one is to assign a key to nil, you can delete the element, and the other is to delete the element by means of the dictionary's Removevalueforkey method, which is the value to be deleted.



There are two methods for dictionary element substitution, one is to assign values directly to an existing key, so that the new value replaces the old value, and the other is replaced by the Updatevalue (Forkey:) method, and the return value of the method is the value to replace.



Let's look at an example:





[HTML]View Plaincopy


var studentdictionary = [102: "Zhang San", 105: "John Doe", 109: "Harry"]①
STUDENTDICTIONARY[110] = "Dong Liu" ②
println ("Class size: \ (studentdictionary.count)") ③
Let dismissstudent = Studentdictionary.removevalueforkey (102) ④
println ("Expelled students: \ (dismissstudent)") ⑤
STUDENTDICTIONARY[105] = Nil⑥
STUDENTDICTIONARY[109] = "Zhang San" ⑦
Let replacestudent = studentdictionary.updatevalue ("John Doe", forkey:110) ⑧
println ("The student replaced is: \ (replacestudent)") ⑨






The output results are as follows:



Class Size: 4



Expelled students: Zhang San



The students to be replaced are: Dong Liu



The above Code section ① is declaring and initializing the dictionary studentdictionary, the ② line code append key is 110, the value is "Dong Liu" an element, the ③ line code is the number of print class students, count is the dictionary property, returns the length of the dictionary.



Line ④ and line ⑥ are all delete elements, the ④ line code is to use the Removevalueforkey method to delete the element, Dismissstudent is the return value, it keeps the deleted element. So we print the output in line ⑤ dismissstudent is "expelled students: Zhang San". Line ⑥ studentdictionary[105] = Nil statement is a direct assignment of nil can also delete 105 corresponding elements.



Line ⑦ and line ⑧ replace the old element, and if the key of line ⑦ does not exist, the result is a new "key-value" pair element appended to the dictionary. Line ⑧ is replaced by the Updatevalue (Forkey:) method, the return value of the method is "Dong Liu", and the ⑨ Line code is printed "The student being replaced is: Dong Liu".



Third, dictionary traversal



The dictionary traversal collection is also an important operation of the dictionary. Unlike arrays, the dictionary has two collections, so the traversal can traverse only the collection of values, or only the collection of keys, or at the same time. These traversal procedures are implemented through a for-in loop.



The following is a sample code that iterates through a dictionary:





[HTML]View Plaincopy



var studentdictionary = [102: "Zhang San", 105: "John Doe", 109: "Harry"]
println ("---traversal key---")
For StudentID in Studentdictionary.keys {①
println ("School Number: \ (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 results of the operation are as follows:



---traversal key---



Study No.: 105



Study No.: 102



Study No.: 109



---traversal value---



Student: John Doe



Student: Zhang San



Student: Harry



---traversal key: Value---



105: John Doe



102: Zhang San



109: Harry



As we can see from the code above, we have 3 ways to traverse the dictionary, all of which use the for in statement. The ① code iterates through the key collection, where keys is a dictionary property and can return a collection of all the keys. The ② line code iterates through a collection of values, where values is a dictionary property and can return a collection of all values. The ③ line code iterates through the dictionary elements that are fetched, (StudentID, Studentname) is a tuple type, which consists of a key variable StudentID and a value variable studentname.








For more information, please visit the first Swift book "Swift Development Guide" book Exchange discussion website: http://www.51work6.com/swift.php Welcome to join Swift Technical discussion group: 362298485








Welcome to Luxgen iOS Classroom public Platform






Swift Dictionary Collection


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.