original articles, welcome reprint. Reprint Please specify: Dongsheng's blog
Swift 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), andThe 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
Swift Dictionary type is Dictionary , which is also a generic collection.
in declaring a Dictionary type, you can use one of the following statements.
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:
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:
var studentdictionary =[102: "Zhang San", 105: "John Doe", 109: "Harry"] print ("---traversal key---") for StudentID Instudentdictionary.keys {pri NT ("study number: \ (StudentID)")} print ("---traverse value---") for studentname instudentdictionary.values {print ("Student: \ (Studentname)")} Print ("---traversal key: Value---") for (Studentid,studentname) in Studentdictionary {print ("\ (StudentID): \ (Studentname)}}
The results of the operation are as follows:
--- Traverse Key ---
School Number: the
School Number: 102
School Number: 109
--- Traversing Values ---
Student: John Doe
Student: Zhang San
Student: Harry
--- Traverse Key : value ---
: John Doe
102: Zhang San
109: Harry
Welcome to follow Dongsheng Sina Weibo@tony_Dongsheng.
Learn about the latest technical articles, books, tutorials and information on the public platform of the smart Jie classroom
650) this.width=650; "title=" 00.png "src=" http://s5.51cto.com/wyfs02/M02/7C/A7/wKiom1bVDq-j3whoAAAs2MBEZnc544.png "alt=" Wkiom1bvdq-j3whoaaas2mbeznc544.png "/>
More ProductsIOS,Cocos, mobile Design course please pay attention to the official website of Chi Jie Classroom:http://www.zhijieketang.com
Smart-Jie Classroom Forum Website:http://51work6.com/forum.php
This article is from the "Dongsheng-ios Technical Consultant" blog, make sure to keep this source http://tonyguan.blog.51cto.com/701759/1746240
Learning Swift from scratch (day 16)--Dictionary collection