2020-03-13 字典的定义(Dictionary)

var dict1 = ["swift":"张三","python":"李四","java":"老王"]
print(dict1)
print(dict1.count)
print(dict1.isEmpty)
print(dict1["swift"]!)

//空字典的定义
var empty1:[Int:String] = [:]
var empty2:Dictionary = [:]
var empty3 = String:String

//字典的特点:1)无序 2)键不能重复
let a = [1:"a",2:"b",3:"c"]
let b = [3:"c",2:"b",1:"a"]
print(a==b)//true

//遍历
for key in dict1.keys{
print(key)
}
for value in dict1.values{
print(value)
}
for (key,value) in dict1{
print(key,value)
}

//添加or修改(如果这个Key当前没有,添加操作;如果当前这个Key存在,修改操作)
var user = ["name":"lw","pwd":"123","job":"student"]
user["name"] = "maotu"
print(user)

//修改
var oldPwd = user.updateValue("456",forKey:"pwd")!//返回原来value的值
if oldPwd == user["pwd"]{
print("修改后的密码与修改前一样,可能会导致安全问题!")
}
print(user)

//添加
user["email"] = "[email protected]"
user.updateValue("chuzhou",forKey:"location")
print(user)

//删除
user.removeValue(forKey:"location")
user["email"] = nil //null
print(user)

你可能感兴趣的:(2020-03-13 字典的定义(Dictionary))