温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

初识Swift集合之字典集合

发布时间:2020-06-27 22:44:06 来源:网络 阅读:479 作者:雾岛千山 栏目:移动开发

字典集合

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

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

    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), ")
    }
}

    



向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI