在 Swift 中,字典是一种无序的集合类型,它将唯一的键映射到对应的值。以下是关于 Swift 字典的基本信息和操作:

创建字典
// 创建空字典
var emptyDictionary = [String: Int]()

// 创建带有默认值的字典
var dictionary = ["one": 1, "two": 2, "three": 3]

// 使用 Dictionary 构造函数创建字典
var anotherDictionary = Dictionary<String, Double>()

访问和修改字典
// 访问值
let value = dictionary["two"]

// 修改值
dictionary["three"] = 30

// 添加键值对
dictionary["four"] = 4

// 移除键值对
dictionary.removeValue(forKey: "one")

字典的常用属性和方法
// 字典键的集合
let keys = Array(dictionary.keys)

// 字典值的集合
let values = Array(dictionary.values)

// 字典元素个数
let count = dictionary.count

// 是否为空
let isEmpty = dictionary.isEmpty

// 遍历字典
for (key, value) in dictionary {
    print("\(key): \(value)")
}

多维字典

Swift 也支持多维字典:
var twoDDictionary = [
    "group1": ["John": 25, "Jane": 30],
    "group2": ["Bob": 22, "Alice": 28]
]
let age = twoDDictionary["group1"]?["John"]

以上是一些 Swift 字典的基本操作。Swift 提供了丰富的字典处理方法,包括合并字典、过滤字典等操作。


转载请注明出处:http://www.zyzy.cn/article/detail/14423/Swift