字典的概念

字典的概念
字典的初始化


//字典的定义
let dic:[String:Any] = ["名称":"liuxh","年龄":18]
print(dic)
字典元素的基本操作

字典元素的基本操作.png
//增
var dict:[String:Any] = ["名称":"liuxh","年龄":18]
dict["性别"] = "男"
print(dict)
//改
dict.updateValue("汉", forKey: "民族")
//["Key"] updateValue 直接修改数值 如果没有发现相应的key 增加键值对 如果发现有相应的key 做修改操作
//删除
dict.removeAll()//删除所有
dict.removeValue(forKey:"性别")//删除 某个键值对
print(dict)
//按索引删除
let index = dict.index(forKey: "民族")
dict.remove(at: index!)
print(dict)
字典的基本操作

字典的基本操作.png
//获取所有的key
let keys = dict.keys
print (keys)
//获取所有的value
let values = dict.values
print (values)
//遍历所有的value
for value in values {
print(value)
}
//遍历所有的key
for key in keys {
print(key)
}
//遍历字典键值对
for (key,value) in dict {
print(key,":",value)
}
//字典合并
let dict2:[String:Any] = ["c":3]
//吧dic2 里面所有的键值对 添加到dict
for (key,value) in dict2 {
dict[key]=value
}
//方法二 添加扩展
let dict3:[String:Any] = Dictionary<String, Any>.addResultDict(dict: dict, dic2: dict2)
print(dict3)
//两个字典相加
let d1:[String:Any] = ["a":1]
let d2:[String:Any] = ["b":2]
let d3 = Dictionary.addResultDict(dict: d1, dic2: d2)
print(d3)
extension Dictionary{
static func addResultDict(dict:Dictionary,dic2:Dictionary) -> Dictionary{
var result = dict
for (key,value) in dic2 {
result[key]=value
}
return result
}
}
网友评论