//字典的定义
var dict1 = ["swift":"雨燕","python":"大蟒","java":"爪哇国"]
//问题:dict1 长度是多少? 3
var dict2:[String:String] = ["swift":"雨燕","python":"大蟒","java":"爪哇国"]
var dict3:Dictionary<String,String> = ["swift":"雨燕","python":"大蟒","java":"爪哇国"]
//空字典的定义
var empty1:[Int:String] = [:]
var empty2:Dictionary<String,String> = [:]
var empty3 = [String:String]()
基本操作:长度,判断是否为空,取值
print(dict1.count)
print(dict1.isEmpty)
print(dict1["java"]!)//返回值是一个可选型,通过!进行解包
//字典的特点:
1.无序
2.键不能重复
let d1 = [1:"a",2:"b",3:"d"]
let d2 = [2:"b",1:"a",3:"d"]
print(d1==d2)//true
//let d3 = [2:"b",1:"a",3:"d",3:"e"] --报错
遍历-遍历 Key,value,key-value对
for key in dict1.keys{
print(key)
}
for value in dict1.values{
print(value)
}
for (key,value) in dict1{
print(key,value)
}
增删改查
//如果这个Key当前没有,添加操作;如果当前这个Key存在,修改操作
//改var
user=["name":"yu","pwd":"123","job":"coder"]
user["job"] = "student"
print(user)
//user.updateValue("456",forKey:"pwd")//更新值
var oldPwd = user.updateValue("456",forKey:"pwd")!//返回原来value的值
if oldPwd == user["pwd"]{
print("修改后的密码与修改前一样,可能会导致安全问题!")
}
print(user)
//添加
user["email"] = "56429@qq.com"
user.updateValue("chuzhou",forKey:"location")
print(user)
//删除
user.removeValue(forKey:"location")
user["email"] = nil //null
print(user)
**总结:
数组:有序的;
set :无序的、唯一性、交集并集等集合专有的操作速度
字典:key-value对