字典集合

字典表示一种非常复杂的集合, 允许按照某个键来访问元素
字典集合的声明与初始化:
var strudentDictionary1 : Dictionary
var strudentDictionary2 = [102 : " Jack" , 105 : "Mark" , 107 : "Jay"] ;
let strudentDictionary3 = [102 : " Jack" , 105 : "Mark" , 107 : "Jay"] ; //let 声明的集合值不可变
var strdentDictionary4 = Dirctionary
字典元素的操作
增,删,改
更改元素
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), ")
}
}另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。