字典的定义
var dict1 = ["swift":"雨燕","python":"大蟒","java":"爪哇国"]
//问题:dict1长度是多少?
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":"miao","pwd":"123","job":"coder"]
user["job"] = "teacher"
print(user)
//user.updateValue("456",forkey:"pwd")//更新值
var oldPwd = user.updateValue("456",forKey:"pwd")!//返回原来的value的值
if oldPwd == user["pwd"]{
print("修改后的密码与修改前一样,可能会导致安全问题!")
}
print(user)
//添加
user["email"] = "1234@qq.com"
user.updateValue("zhongguo",forKey:"location")
print(user)
//删除
user.removeValue(forKey:"location")
user["email"] = nil //null
print(user)
//总结:什么时候我们采取那种类型?
//数组:有序的;
//set:无序、唯一性、交集并集等集合专有的操作速度快
//字典:key-value对
//for in遍历