Z
ZHANK
集合类型

字典 Dictionary

字典创建/访问、下标返回可选值、合并 merge、默认值

字典 Dictionary

Swift 字典访问返回可选值——因为 key 可能不存在。default 下标和 merge 是实用功能。

学完本章你将: 掌握字典创建/访问、可选索引、merge、default。


创建与访问

swift
var scores = ["数学": 92, "语文": 88]
var empty = [String: Int]()

// 访问返回 Optional——因为 key 可能不存在
let math = scores["数学"]   // Optional(92)
let english = scores["英语"] // nil

// 安全访问
if let score = scores["数学"] {
    print(score)  // 92
}

// 带默认值
let engScore = scores["英语", default: 0]  // 0

增删改

swift
scores["英语"] = 85        // 添加
scores["数学"] = 95        // 修改
scores.updateValue(90, forKey: "数学")  // 返回旧值(Optional)
scores.removeValue(forKey: "语文")      // 返回被删除的值

// 遍历
for (subject, score) in scores {
    print("\(subject): \(score)")
}

merge 合并

swift
let newScores = ["物理": 88, "化学": 91]

// 合并(冲突时取新值)
scores.merge(newScores) { _, new in new }

// 合并(冲突时取旧值)
scores.merge(newScores) { old, _ in old }