importFoundation
//字典:字典是一个无序集合,用来存储具有一一对应关系的数据,比如说name-张三,gender-male,age-16(key-value键值对)
//字典类Dictionary,字面量创建的方式也是中括号[key1:value1,key2:value2,...]多个键值对之间用逗号隔开
//数组:[element1,element2,...]
//使用字典的时候必须明确字典中的key-value具体的数据类型
//创建一个key为String,value为String的一个空字典
//[String:String]表示一个key为String,value为String的一个字典类型,后面的小括号表示初始化
letdict = [String:String]()
letdict1:[String:Int] = ["age":18,"count":20,"grade":5]
letdict2:[String:String] = ["name":"张三","gender":"male"]
print(dict1)
print("\n")
print(dict2)
print("\n")
//通过key值来获取对应的value:dict[key]
//通过key值来获取到的value值是一个可选类型
letage =dict1["age"]
letgen =dict2["gender"]
print(age!,gen!)
print("\n")
//获取所有的key值和所有的value值
letkeys =dict2.keys
letvalues =dict2.values
//遍历所有的key值
forkeyinkeys{
print(key)
}
//遍历所有的value值
forvalueinvalues{
print(value)
}
//字典遍历
for(key,value)indict2{
print("key =\(key),value =\(value)\n")
}
//
lettempDict = ["key1":"value1","key2":"value2","key3":"value2","key4":"value2",]
//遍历打印key和value分别为key2,value2的键值对
for(key,value)intempDict{
ifkey =="key2"&& value =="value2"{
print(key,value)
}
}
print("\n")
//学习错误:注意key与value是局部变量,可以取值为任意数,比如a,b
//字典同样分为可变字典(var)和不可变字典(let)
//可变字典可以增减删除键值对
varmDict:[String:Int] = ["age":18]
//增减键值对: grade:5
//字典[key] = [value]:如果key存在的话这就是更新键值对的操作,如果不存在的话就是一个增加键值对的操作
print("mDict =\(mDict)\n")
mDict["grade"] =5
print("mDict =\(mDict)\n")
mDict["grade"] =6
print("mDict =\(mDict)\n")
//合并两个字典
letdict11 = ["name":"李四","gender":"male"]
vardict22 = ["grade":"5","phone":"1234567","name":"张三"]
//最笨的方式
//dict22["name"] = "李四"
//dict22["gender"] = "male"
//遍历方法
for(key,value)indict11{
dict22[key] = value
}
print("dict22 =\(dict22)\n")
//删除
dict22.removeAll(keepCapacity:true)//移除所有的value值后是否保存内存大小
//removeValueForKey,根据一个key值来移除键值对
dict22.removeValueForKey("name")
print("dict22 =\(dict22)\n")
//2016.10.25 afternoon
//新建一个字典,存储下面信息:
/*
C:成龙:123,陈小春:234,陈冠希:345
D:大S:456
F:范冰冰567,发哥678
Z:甄子丹789,钟镇伟890
*/
//错误在于:key值不能重复
//let ndict:[String:String] = ["C":"成龙","C":"陈小春","C":"陈冠希","D":"大S","F":"范冰冰","F":"发哥",
//"Z":"甄子丹","Z":"钟镇伟"]
//字典里面再包含一个字典
letnameDict:[String:[String:Int]] = ["C":["成龙":123,"陈小春":234,"陈冠希":345],"D":["大S":456],"F":["范冰冰":567,"发哥":678],"Z":["甄子丹":789,"钟镇伟":890]]
print("nameDict =\(nameDict)\n")