Swift 2.0 learning notes (Day 16)-dictionary set

Source: Internet
Author: User

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

 

 

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.