字典的定义
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=[String:String]()
var empty3:Dictionary<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":"yue","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"] = "38243@qq.com"
user.updateValue("fuyang",forKey:"location")
print(user)
//删除
user.removeValue(forKey:"location")
user["email"] = nil //null
print(user)
总结:什么时候我们采用哪种类型?
数组:有序性;
Set:无序、唯一性、交集并集等集合专有的操作速度高
字典:Key-value对
//for 遍历