1、字典的定义
//方法一
let dict1 = ["a":12,"b":13]
//方法二
//如果key-value 的数据类型不一致用以下方法
let dict2 = ["name":"张","age":18] as [String : Any]
上面定义字典省略了Dictionary<String,Int>
//方法三
let dict3:Dictionary<String,Int> = ["a":12,"b":14]
//方法四
let dict4:[Int:String] = ["a":12,"b":13,"c":14]
2、空字典的定义
//第一种
var dict1:[Int:String]=[:]
//第二种
var dict2:Dictionary=[:]
//第三种
var dict13=[Int:String]()
3、基本操作
var dict1=["a":12,"b":13,"c":14]
print(dict1.count) //打印数组长度
print(dict1.isEmpty) //判断值是否为空
print(dict1[1]!) //取值 (返回值是一个可选型,通过!进行解包)
//字典的特点:
1)无序
2)键不能重复
let dict1=["a":12,"b":13,"c":14]
let dict2=["a":12,"c":14,"b":13]
print(dict1==dict2)//判断是否一致
4、遍历
let dict:Dictionary<String,Any> = ["name":"张三","age":14,"title":"老板"]
//遍历元组
let e: (key: String, value: Any)
for e in dict {
print("\(e.key) \(e.value)")
}
方法二
print("-------同时遍历key和value")
for (kkk,vvv) in dict {
print("\(kkk) \(vvv)")
}
//enumerated() 枚举
print("-------同时遍历key和value和索引")
for (kkk,vvv) in dict.enumerated() {
print("\(kkk) \(vvv)")
}
5、增删改查
往字典里面增加一个元素
var dict = ["name":"张三","age":18] as [String : Any]
dict["title"] = "李四"
print(dict)
字典里面修改一个元素
var dict = ["name":"张三","age":18] as [String : Any]
// dict["title"] = "李四"
dict["name"]="王老五"
print(dict)
//如果key存在就是修改,不存在就是新增。
字典里面删除一个元素
var dict = ["name":"张三","age":18] as [String : Any]
//方法一
//找到元素所在的位置
if let index = dict.index(forKey: "age") {
//删除这个位置对应的元素
let olditem = dict.remove(at: index)
}
print(dict)
//方法二
var dict = ["name":"张三","age":18] as [String : Any]
dict.removeValue(forKey: "age")
print(dict)
总结:什么时候我们采用哪种类型?
数组:有序的;
set: 无序、唯一性、交集并集等集合专有的操作速度高
字典:key-value对