字典的定义
var dict1 = ["swift":"雨燕","python":"大蟒","java":"爪哇国"]
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
遍历-遍历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)
}
增删改查
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"] = "56429@qq.com"
user.updateValue("chuzhou",forKey:"location")
print(user)
//删除
user.removeValue(forKey:"location")
user["email"] = nil //null
print(user)