1、Dictionary<Key, Value> 或者 [Key:Value]
2、特性
a.字典是一种存储多个相同类型的值的容器;
b.每个值(value)都关联唯一的键(key);
c.字典中的数据项并没有具体顺序;
1.创建
var tempDic : Dictionary<Int, String>
var tempDic1 = [Int: String]()
//用字典字面量创建字典
var airports: [String: String] = ["key1": "1", "key2": "2"]
var airports1 = ["key1": "1", "key2": "2"]
2、长度
var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]
print(tempDic1.count) //3
3.是否为空
var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]
if !tempDic1.isEmpty {
print("数组不为空")
}
4.增
var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]
tempDic1["key4"] = "4"
print(tempDic1)
//["key2": "2", "key3": "3", "key4": "4", "key1": "1"]
5.删
var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]
tempDic1.removeValue(forKey: "key1")
print(tempDic1) //["key2": "2", "key3": "3"]
6.改
var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]
tempDic1["key1"] = "a"
print(tempDic1) //["key2": "2", "key3": "3", "key1": "a"]
//updateValue 返回更新值之前的原值; 可选类型
var element1 :String? = tempDic1.updateValue("1", forKey: "key1")
print(element1) // Optional("a")
7.字典遍历
var tempDic1 :[String: String] = ["key2": "2", "key3": "3"]
for(key,value) in tempDic1{
print("\(key) : \(value)")
}
//key2 : 2
//key3 : 3
//遍历keys
for key in tempDic1.keys{
print(key)
}
//key2
//key3
//遍历values
for value in tempDic1.values{
print(value)
}
//2
//3
8.某个字典的键值合构型一个数组
var tempDic1 :[String: String] = ["key2": "2", "key3": "3"]
let keysArr = [String](tempDic1.keys)
print(keysArr) //["key2", "key3"]
9.keys 或 values排序
print(tempDic1.keys.sorted())
网友评论