Dictionary Collection
A dictionary represents a very complex collection that allows you to access an element by a key
Declaration and initialization of a dictionary collection:
var strudentdictionary1:dictionary<int, string> = [102: "Jack", "Mark", 107: "Jay"]; This declares a collection of StrudentDictionary1 dictionaries whose keys are of type Int and whose value is string type
var strudentDictionary2 = [102: "Jack", "Mark", 107: "Jay"];
Let StrudentDictionary3 = [102: "Jack", "Mark", 107: "Jay"]; The set value of let declaration is not variable
var strdentDictionary4 = Dirctionary<int, string> (); Declares an empty collection of strudentdictionary
Manipulation of dictionary elements
increase, delete, change
Change element
STRUDENTDICTIONARY[102] = "10 Yuan";
Delete Element
Let dismisssstrudent = Strudentdictionary.removevalueforkey (102); Deletes the element of the specified key, using this method to delete the element, which returns the value of the deleted collection. If you do not return a value Strudentdictionary.removevalueforkey (102)
Strudentdictionary[105]=nil//This allows you to delete elements directly
Note Here a special method Updatevalue (value, Forkey: Key), if the corresponding key is not found, it will increase the value, if the value is found, it will replace the value. This function also returns values that have been replaced or added.
Let replacestrudent = Strudentdictionary.updatevalue ("10 Yuan", forkey:10);
can also write: Strudentdictionary.updatevalue ("10 Yuan", forkey:10);
The traversal of the dictionary collection, he is divided into key traversal, value traversal, key and value face changing
var studentdictionary = [102 : "Zhang San" , 105 : "Zhang San" , 109 : "Harry"]var i = 0 ;p rintln ("------Traversal value------") ;for studentid in studentdictionary.keys { i++ ; if (i <= &NBSP;2) { print ("Study No.: \ (StudentID), ") }else { println ("School Number: \ (StudentID)") &NBSP;}}PRINTLN ("------Traverse value------") ;for studentValue in studentDictionary.values { i-- ; if (i > 0) { print ("Name: \ (studentvalue), ") }else { println ("Name: \ (studentvalue)") }}println ("------Traversal ID and value------") ;for (Studentid, studentvalue) in studentdictionary { i ++ ; if (i <= 2) { print ("\ (StudentID): \ (studentvalue), ") }else { println ("\ (StudentID): \ (studentvalue), ") }}
This article is from the "10 Yuan" blog, please be sure to keep this source http://tenyuan.blog.51cto.com/9401521/1620720
A collection of dictionaries for the first knowledge of Swift collection