1.Swift 字典用来存储无序的相同类型数据的集合,Swift 字典会强制检测元素的类型,如果类型不同则会报错。
2.Swift 字典每个值(value)都关联唯一的键(key),键作为字典中的这个值数据的标识符。
3.Swift 字典的key没有类型限制可以是整型或字符串,但必须是唯一的。
字典的定义
var dictionary1 = ["redtea":"红茶","greentea":"绿茶","scentedtea":"花茶"]
//问题:dict1 长度是多少? 3
var dictionary2:[String:String] = ["redtea":"红茶","greentea":"绿茶","scentedtea":"花茶"]
var dictionary3:Dictionary<String,String> = ["redtea":"红茶","greentea":"绿茶","scentedtea":"花茶"]
空字典的定义
var empty1:[Int:String] = [:]
var empty2:Dictionary<String,String> = [:]
var empty3 = [String:String]()
基本操作:长度,判断是否为空,取值
print(dictionary1.count)
print(dictionary1.isEmpty)
print(dictionary1["scentedtea"]!)//返回值是一个可选型,通过!进行解包
//字典的特点:1)无序 2)键不能重复
let s1 = [1:"a",2:"b",3:"d"]
let s2 = [2:"b",1:"a",3:"d"]
print(s1==s2)//true
//let s3 = [2:"b",1:"a",3:"d",3:"e"] --报错
字典遍历
for key in dictionary1.keys{
print(key)
}
for value in dictionary1.values{
print(value)
}
for (key,value) in dictionary1{
print(key,value)
}
增删改查
//如果这个Key当前没有,添加操作;如果当前这个Key存在,修改操作
//改元素
var user = ["name":"yjl","pwd":"666","job":"Student"]
user["job"] = "programmer"
print(user)
//user.updateValue("888",forKey:"pwd")//更新值
var oldPwd = user.updateValue("888",forKey:"pwd")!//返回原来value的值
if oldPwd == user["pwd"]{
print("修改后的密码与修改前一样,可能会导致安全问题!")
}
print(user)
//添加元素
user["email"] = "3184933412@qq.com"
user.updateValue("jieshou",forKey:"location")
print(user)
//删除元素
user.removeValue(forKey:"location")
user["email"] = nil //null
print(user)