Swift字典表示一种很是复杂的集合,容许按照某个键来访问元素。字典是由两部分集合构成的,一个是键(key)集合,一个是值(value)集合。键集合是不能有重复元素的,而值集合是能够重复的,键和值是成对出现的。网站
字典声明与初始化设计
Swift字典类型是Dictionary,也是一个泛型集合。get
在声明一个Dictionary类型的时候可使用下面的语句之一。it
- var studentDictionary1: Dictionary<Int, String>
- var studentDictionary2: [Int: String]
声明的字典须要进行初始化才能使用,字典类型每每是在声明的同时进行初始化的。示例代码以下:io
- var studentDictionary1: Dictionary<Int, String>
- Ê= [102 : "张三",105 : "李四", 109 : "王五"]
- var studentDictionary2 = [102 : "张三",105 : "李四", 109 : "王五"]
-
- let studentDictionary3 = [102 : "张三",105 : "李四", 109 : "王五"]
-
字典遍历ast
字典遍历过程能够只遍历值的集合,也能够只遍历键的集合,也能够同时遍历。这些遍历过程都是经过for-in循环实现的。class
下面是遍历字典的示例代码:泛型
- 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)")
- }
运行结果以下:循环
---遍历键---遍历
学号:105
学号:102
学号:109
---遍历值---
学生:李四
学生:张三
学生:王五
---遍历键:值---
105 : 李四
102 : 张三
109 : 王五
更多精品iOS、Cocos、移动设计课程请关注智捷课堂官方网站:http://itlanbao.com/preview.aspx#1,0