//定义方法
var dict1 = ["swift":"雨燕","python":"大蟒","java":"爪洼国"]
var dict2:[String:String] = ["swift":"雨燕","python":"大蟒","java":"爪洼国"]
var dict3:Dictionary<String,String> = ["swift":"雨燕","python":"大蟒","java":"爪洼国"]//空字典的定义
var emty1:[Int:String] = [:]
var emty2:Dictionary<String,String> = [:]
var emty3 = [String:String]()//基本操作:长度判断是否为空,取值
print(dict1.count)
print(emty1.isEmpty)
print(dict1["swift"]!)//返回h值可选型,!解包//字典的特性:1、无序 2、键不能重复
let d1 = ["1":"a","2":"b","3":"c"]
let d2 = ["3":"c","2":"b","1":"a"]
if d1 == d2 {
print("d1等于d2")
} else {
print("d1不等于d2")
}
print(d1 == d2)
//let d3 = ["1":"a","2":"b","3":"c","3":"r"]//报错,键相同
//遍历 - 遍历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":"jing","pwd":"123","job":"student"]
user["pwd"] = "321"
print(user)
//user.updateValue("789",forKey:"pwd")//更新值
var oldPwd = user.updateValue("789",forKey:"pwd")//第二种方法,返回原来的value值
if oldPwd == user["pwd"]{
print("密码与修改前一样,可能会有风险")
}else{
print("修改成功")
}
print(user)
// 增
user["email"] = "148@qq.com"
user.updateValue("xuexiao",forKey:"school")
print(user)//删除
user.removeValue(forKey:"job")
user["email"] = nil//null
print(user)