Dictionary 的操作

优质
小牛编辑
125浏览
2023-12-01

Swift 5.x Dictionary 的操作


1.添加或更新元素 updateValue(_:forKey:)

var dict = ["zhangsan": 11, "lisi": 19, "wangwu": 20]
dict.updateValue(18, forKey: "zhangsan")
print(dict)
var dict = ["zhangsan": 11, "lisi": 19, "wangwu": 20]
dict["zhangsan"] = 18
print(dict)

输出结果:

["lisi": 19, "wangwu": 20, "zhangsan": 18]

2. 移除元素 removeValue(forKey:)

var dict = ["zhangsan": 11, "lisi": 19, "wangwu": 20]
dict["zhangsan"] = nil
print(dict)
var dict = ["zhangsan": 11, "lisi": 19, "wangwu": 20]
dict.removeValue(forKey: "zhangsan")
print(dict)

输出结果:

["lisi": 19, "wangwu": 20]

3. 合并两个字典 merge(_:uniquingKeysWith:)

var dictionary1 = ["a": 1, "b": 2]
var dictionary2 = ["a": 3, "c": 4]
dictionary1.merge(dictionary2) { (current, _) -> Int in current }
print(dictionary1)

var dictionary3 = ["a": 5, "d": 6]
dictionary1.merge(dictionary3) { (_, new) -> Int in new }
print(dictionary1)

输出结果:

["c": 4, "b": 2, "a": 1]
["c": 4, "b": 2, "a": 5, "d": 6]

4. firstIndex

  • 虽然字典是无序的, 但是每个kv对在扩容之前的位置是稳定的.
let imagePaths = ["star": "/glyphs/star.png",
                  "portrait": "/images/content/portrait.jpg",
                  "spacer":"/images/shared/spacer.gif"]
let glyphIndex = imagePaths.firstIndex(where: {$0.value.hasPrefix("/glyphs")})

if let index = glyphIndex {
    print(index)
    print("The '\(imagePaths[index].key)' image is a glyph.")
} else {
    print("No glyphs found!")
}

输出结果:

Index(_variant: Swift.Dictionary<Swift.String, Swift.String>.Index._Variant.native(Swift._HashTable.Index(bucket: Swift._HashTable.Bucket(offset: 0), age: -1155010198)))
The 'star' image is a glyph.