Swift 字典的创建与操作

1、字典的概念

  • 字典储存无序的互相关联的同一类型的键和同一类型的值的集合
  • 字典类型的全写方式 Dictionary<Key, Value>,简写方式 [Key: Value],建议使用简写方式
  • 字典的 key 必须是可哈希的

2、创建空字典

  • 初始器方式
  • 简写方式
  • 字面量方式
//初始化器
let dict1 = Dictionary<String, Int>()
//简写方式
let dict2 = [String: Int]()
//字面量
let dict3: Dictionary<String, Int> = [:]
let dict4 = ["zhangsan": 18, "lisi": 24, "wangwu": 34]

3、count 和 isEmpty

  • 可以使用 count 只读属性来找出 Dictionary 拥有多少元素
  • 使用布尔量 isEmpty 属性检查字典是否为空
let dict4 = ["zhangsan": 18, "lisi": 24, "wangwu": 34]
print(dict4.count)
print(dict4.isEmpty)

4、遍历字典

  • For-In 循环
  • 可以通过访问字典的 keys 和 values 属性来取回可遍历的字典的键或值的集合
  • Swift 的 Dictionary 类型是无序的。要以特定的顺序遍历字典的键或值,使用键或值的 sorted() 方法
let dict = ["zhangsan": 18, "lisi": 24, "wangwu": 34]
for (keys, values) in dict {
    print("keys : \(keys), values : \(values)")
}

for key in dict.keys.sorted() {
    print("key : \(key), value : \(dict[key])")
}

5、字典常用操作

1> 添加或更新元素

  • 使用下标添加或更新元素
  • 使用 updateValue(_:forKey:) 方法添加或更新元素,返回一个字典值类型的可选项值
var dict = ["zhangsan": 18, "lisi": 24]
dict.updateValue(25, forKey: "wangwu")
print(dict.prefix(upTo: dict.startIndex))  //获取字典切片
print(dict)

2> 移除元素

  • 使用下标脚本语法给一个键赋值 nil 来从字典当中移除一个键值对
  • 使用 removeValue(forKey:)来从字典里移除键值对。这个方法移除键值对如果他们存在的 话,并且返回移除的值,如果值不存在则返回 nil
var dict = ["zhangsan": 18, "lisi": 24, "wangwu": 25]
//dict.remove(at: dict.startIndex)
//dict.removeValue(forKey: "lisi")
//dict.removeAll()
dict.removeAll(keepingCapacity: true)
print(dict.capacity)
print(dict)

3> 合并两个字典

  • merge(_:uniquingKeysWith:)
var dict = ["a": 1, "b": 2]
let dict2 = dict.merging(["a": 3, "c": 4]) { (current, _) -> Int in current }
print(dict2)

let dict3 = dict.merging(["a": 5, "d": 6]) { (_, new) -> Int in
    new
}
print(dict3)

4> firstIndex

  • 虽然字典是无序的,但是每个kv对在扩容之前的位置是稳定的。如果你需要保持顺序的kv对 可以使用 KeyValuePairs
let dict: KeyValuePairs = [
    "Math": 89,
    "Chinese": 87,
    "English": 78
]
print(dict.first!)
print(dict)  //完全按书写的顺序输出

5> 字典另外一些常用操作

let dict = [
    "Math": 89,
    "Chinese": 87,
    "English": 78
]
print(dict.contains(where: { $0.value == 89}))
print(dict.allSatisfy({ $0.key == "Math"}))
print(dict.contains(where: { (dict) -> Bool in
    dict.key == "Math"
}))
print(dict.min(by: { (dict1, dict2) -> Bool in
    dict1.value < dict2.value
}))
print(dict.max(by: { $0.value < $1.value }))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值