您的位置:首页 > 移动开发 > Swift

Swift 2.0学习笔记(Day 16)——字典集合

2015-09-23 10:30 369 查看
原创文章,欢迎转载。转载请注明:关东升的博客 Swift字典表示一种非常复杂的集合,允许按照某个键来访问元素。字典是由两部分集合构成的,一个是键(key)集合,一个是值(value)集合。键集合是不能有重复元素的,而值集合是可以重复的,键和值是成对出现的。字典声明与初始化 Swift字典类型是Dictionary,也是一个泛型集合。 在声明一个Dictionary类型的时候可以使用下面的语句之一。
var studentDictionary1: Dictionary<Int, String>

var studentDictionary2: [Int: String]
声明的字典需要进行初始化才能使用,字典类型往往是在声明的同时进行初始化的。示例代码如下:
var studentDictionary1: Dictionary<Int, String> 

          Ê= [102 : "张三",105 : "李四", 109 : "王五"]

var studentDictionary2 = [102 : "张三",105 : "李四", 109 : "王五"]

 let studentDictionary3 = [102 : "张三",105 : "李四", 109 : "王五"]
字典遍历 字典遍历过程可以只遍历值的集合,也可以只遍历键的集合,也可以同时遍历。这些遍历过程都是通过for-in循环实现的。 下面是遍历字典的示例代码:
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 : 王五
欢迎关注关东升新浪微博@tony_关东升。关注智捷课堂微信公共平台,了解最新技术文章、图书、教程信息

更多精品iOS、Cocos、移动设计课程请关注智捷课堂官方网站:http://www.zhijieketang.com 智捷课堂论坛网站:http://51work6.com/forum.php
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: