初识Swift集合之字典集合

字典集合

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

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

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

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

let strudentDictionary3 =[102 : " Jack",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) ;

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

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


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

println("------遍历Idandvalue------");
for(studentId,studentValue)instudentDictionary{
i++;
if(i<=2){
print("\(studentId):\(studentValue),")
}else{
println("\(studentId):\(studentValue),")
}
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...