字典的基本使用
// key一定是可以hash的(String,Int,Double,Bool),value没有要求
// ps: 字典是通过key来定位的, 所有的key必须是可以 hash/哈希 的 (MD5是一种哈希, 哈希就是将字符串变成唯一的整数, 便于查找, 能提高字典遍历的速度)
var dict = ["name":"芳草天","age":25] as Any
print(dict)
var dict2:Dictionary<String,AnyObject> = ["name":"芳草天" as AnyObject,"age":25 as AnyObject]
print(dict2)
var dict3:[String:AnyObject] = ["name":"路飞" as AnyObject,"age":25 as AnyObject]
print(dict3)
//1.字典的定义使用[key:value,key:value]快速定义
let dic:[String:Any] = ["name":"娜美","age":18]
print(dic)
// 数组字典
let arrDic :[[String:Any]] = [
["name":"乔巴","age":12],
["name":"弗兰克","age":24]
]
print(arrDic)
// 可变字典的增删改查
var dictionary:[String:Any] = ["name":"罗宾","age":18]
print(dictionary)
// key存在则为修改,key不存在则为添加
// 增加键值对
dictionary["score"] = 100
print(dictionary)
// 修改键值对
dictionary["name"] = "乌索普"
print(dictionary)
// 删除键值对
dictionary.removeValue(forKey: "name")
print(dictionary)
// 字典遍历
//写法一
for e in dictionary
{
print("key = \(e.key) value = \(e.value)")
}
//写法二
for (key,value) in dictionary
{
print("key = \(key) value = \(value)")
}
// 字典合并
var dic5 = ["name":"山治","age":22] as [String:Any]
let dic6 = ["names":"萨博"]
for (key,value) in dic6
{
dic5[key] = value
}
print(dic5)
//
网友评论