码迷,mamicode.com
首页 > 编程语言 > 详细

初识Swift集合之字典集合

时间:2015-03-16 11:15:53      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:初识swift集合之字典集合

字典集合

    字典表示一种非常复杂的集合, 允许按照某个键来访问元素

字典集合的声明与初始化:

    var strudentDictionary1 : Dictionary<Int , String> = [102 : " Jack" , 105 : "Mark" , 107 : "Jay"] ; //这里声明里一个strudentDictionary1 的字典集合,他的键是 Int 类型,他的值为String类型

    var strudentDictionary2 = [102 : " Jack" , 105 : "Mark" , 107 : "Jay"] ;

    let strudentDictionary3 = [102 : " Jack" , 105 : "Mark" , 107 : "Jay"] ; //let 声明的集合值不可变

    var strdentDictionary4 = Dirctionary<Int , String> (); //声明一个空的strudentDictionary 集合


字典元素的操作

    增,删,改

更改元素

    strudentDictionary[102] = "十元" ;

删除元素

    let dismisssStrudent = strudentDictionary.removeValueForKey(102) ; //删除指定键的元素,使用这个方法删除元素,它会返回被删除集合的值。如果不要返回值strudentDictionary.removeValueForKey(102)

   strudentDictionary[105]=nil  //这样可以直接删除元素

 这里需要注意一个特殊的方法updateValue(值,forKey : 键),如果找不到相对应的键,它会增加值;如果找到这个值,它会替换这个值。这个函数也会返回被替换或者增加 的值。

    let replaceStrudent = strudentDictionary.updateValue("十元" , forKey : 10) ;

    也可以这么写:strudentDictionary.updateValue("十元" , forKey : 10) ;

字典集合的遍历,他分为键遍历、值遍历、键和值变脸

var studentDictionary = [102 : "张三" , 105 : "张三" , 109 : "王五"]
var i = 0 ;
println("------遍历值------") ;
for studentId in studentDictionary.keys {
    i++ ;
    if(i <= 2){
        print("学号:\(studentId), ")
    }else {
        println("学号:\(studentId)")
    }
}


println("------遍历value------") ;
for studentValue in studentDictionary.values {
    i-- ;
    if(i > 0){
        print("姓名:\(studentValue), ")
    }else {
        println("姓名:\(studentValue)")
    }
}

println("------遍历Id and value------") ;
for (studentId, studentValue) in studentDictionary {
    i++ ;
    if (i <= 2) {
        print("\(studentId):\(studentValue), ")
    }else {
        println("\(studentId):\(studentValue), ")
    }
}

    



本文出自 “十元” 博客,请务必保留此出处http://tenyuan.blog.51cto.com/9401521/1620720

初识Swift集合之字典集合

标签:初识swift集合之字典集合

原文地址:http://tenyuan.blog.51cto.com/9401521/1620720

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!