原創文章,歡迎轉載。轉載請註明:關東昇的博客 php
Swift字典表示一種很是複雜的集合,容許按照某個鍵來訪問元素。字典是由兩部分集合構成的,一個是鍵(key)集合,一個是值(value)集合。鍵集合是不能有重複元素的,而值集合是能夠重複的,鍵和值是成對出現的。java
字典聲明與初始化微信
Swift字典類型是Dictionary,也是一個泛型集合。網站
在聲明一個Dictionary類型的時候可使用下面的語句之一。spa
var studentDictionary1: Dictionary<Int, String> var studentDictionary2: [Int: String]
聲明的字典須要進行初始化才能使用,字典類型每每是在聲明的同時進行初始化的。示例代碼以下:.net
var studentDictionary1: Dictionary<Int, String> Ê= [102 : "張三",105 : "李四", 109 : "王五"] var studentDictionary2 = [102 : "張三",105 : "李四", 109 : "王五"] let studentDictionary3 = [102 : "張三",105 : "李四", 109 : "王五"]
字典遍歷設計
字典遍歷過程能夠只遍歷值的集合,也能夠只遍歷鍵的集合,也能夠同時遍歷。這些遍歷過程都是經過for-in循環實現的。code
下面是遍歷字典的示例代碼:教程
var studentDictionary = [102 : "張三",105 : "李四", 109 : "王五"] print("---遍歷鍵---") for studentID in studentDictionary.keys { print("學號:\(studentID)") } print("---遍歷值---") for studentName in studentDictionary.values { print("學生:\(studentName)") } print("---遍歷鍵:值---") for (studentID, studentName) in studentDictionary { print ("\(studentID) : \(studentName)") }
運行結果以下:ci
---遍歷鍵---
學號:105
學號:102
學號:109
---遍歷值---
學生:李四
學生:張三
學生:王五
---遍歷鍵:值---
105 : 李四
102 : 張三
109 : 王五
歡迎關注關東昇新浪微博@tony_ 關東昇。
關注智捷課堂微信公共平臺,瞭解最新技術文章、圖書、教程信息
更多精品iOS、Cocos、移動設計課程請關注智捷課堂官方網站:http://www.zhijieketang.com
智捷課堂論壇網站:http://51work6.com/forum.php