1. 创建字典:
// 声明一个空字典
var emptyDictionary: [String: Int] = [:]
// 使用字面量创建字典
var person = ["name": "John", "age": 25, "city": "New York"]
2. 访问和修改字典:
// 通过键访问值
let name = person["name"]
// 修改值
person["age"] = 26
// 添加新的键值对
person["gender"] = "Male"
// 移除键值对
person["city"] = nil
3. 遍历字典:
for (key, value) in person {
print("\(key): \(value)")
}
// 遍历键
for key in person.keys {
print("Key: \(key)")
}
// 遍历值
for value in person.values {
print("Value: \(value)")
}
4. 检查字典是否为空:
if person.isEmpty {
print("字典为空")
} else {
print("字典不为空")
}
5. 获取字典中键或值的数量:
let numberOfKeys = person.count
6. 使用字典的合并操作符:
var dictionary1 = ["a": 1, "b": 2]
let dictionary2 = ["b": 3, "c": 4]
// 将 dictionary2 合并到 dictionary1 中
dictionary1.merge(dictionary2) { (current, _) in current }
如果键冲突,合并时可指定一个闭包来确定保留哪个值。
这些是字典的一些基本操作。字典在 Swift 中是非常有用的数据结构,适用于存储和检索键值对。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6844/Swift