swift字典集合-备

 Swift字典表示一种非常复杂的集合,允许按照某个键来访问元素。字典是由两部分集合构成的,一个是键(key)集合,一个是值(value)集合。键集合是不能有重复元素的,而值集合是可以重复的,键和值是成对出现的。

字典声明与初始化

  Swift字典类型是Dictionary,也是一个泛型集合。

 在声明一个Dictionary类型的时候可以使用下面的语句之一。

[html]  view plain  copy
 print?在CODE上查看代码片派生到我的代码片
  1. var studentDictionary1: Dictionary<Int, String>  
  2.   
  3. var studentDictionary2: [Int: String]  

          声明的字典需要进行初始化才能使用,字典类型往往是在声明的同时进行初始化的。示例代码如下:

 

 

 

    

[html]  view plain  copy
 print?在CODE上查看代码片派生到我的代码片
  1. var studentDictionary1: Dictionary<Int, String>   
  2.   
  3.           Ê= [102 : "张三",105 : "李四", 109 : "王五"]  
  4.   
  5. var studentDictionary2 = [102 : "张三",105 : "李四", 109 : "王五"]  
  6.   
  7.  let studentDictionary3 = [102 : "张三",105 : "李四", 109 : "王五"]  

 字典遍历

 

 

 

 字典遍历过程可以只遍历值的集合,也可以只遍历键的集合,也可以同时遍历。这些遍历过程都是通过for-in循环实现的。

 下面是遍历字典的示例代码:

 

[html]  view plain  copy
 print?在CODE上查看代码片派生到我的代码片
  1. var studentDictionary = [102 : "张三",105 : "李四", 109 : "王五"]  
  2.   
  3. print("---遍历键---")  
  4.   
  5. for studentID in studentDictionary.keys {   
  6.   
  7.     print("学号:\(studentID)")  
  8.   
  9. }  
  10.   
  11. print("---遍历值---")  
  12.   
  13. for studentName in studentDictionary.values {  
  14.   
  15.     print("学生:\(studentName)")  
  16.   
  17. }  
  18.   
  19.    
  20.   
  21. print("---遍历键:值---")  
  22.   
  23. for (studentID, studentName) in studentDictionary {  
  24.   
  25.     print ("\(studentID) : \(studentName)")  
  26.   
  27. }  

 

 

 

运行结果如下:

---遍历键---

学号:105

学号:102

学号:109

---遍历值---

学生:李四

学生:张三

学生:王五

---遍历键:值---

105 : 李四

102 : 张三

109 : 王五

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值