基础知识六:字典

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())
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 53.计算字符 在字符串中获取字符值的数量, 可以使用字符串字符属性中的计数属性: let unusualMena...
    无沣阅读 1,150评论 0 4
  • 数组的概述 PHP 中的数组实际上是一个有序图。图是一种把 values 映射到 keys 的类型。此类型在很多方...
    dptms阅读 1,638评论 0 4
  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young阅读 3,922评论 1 10
  • 我这里在下雨 你那里怎么样 是否好些了 找到了对的生活对的人 而且学着冷酷一点? 我确实还过的可以 工作充实伙食合...
    老晁阅读 175评论 0 2
  • A姑娘很久以前看到匡匡的《时有女子》,最后一段是:“我一生渴望被人收藏好,妥善安放,细心保存。免我惊,免我苦,免我...
    徽喵阅读 326评论 0 4