在 Swift 中,可以使用 Dictionary(字典)类型来创建和操作键值对。字典是一种无序的集合类型,它存储的是相同类型的多个值,并使用唯一的键来标识和访问这些值。

以下是使用字典的一些常见操作:

  1. 创建字典:
// 创建一个空字典
var emptyDict: [String: Int] = [:]

// 创建一个字典并指定初始值
var dict = ["apple": 5, "banana": 3, "orange": 2]
  1. 添加和修改键值对:
// 添加键值对
dict["grape"] = 4

// 修改键对应的值
dict["apple"] = 6
  1. 访问值:
let count = dict["apple"] // 读取键对应的值

// 使用可选绑定来安全地访问值
if let count = dict["apple"] {
    print("苹果的数量为:\(count)")
}
  1. 删除键值对:
dict["banana"] = nil // 删除键值对
dict.removeValue(forKey: "orange") // 使用 removeValue(forKey:) 方法删除键值对
  1. 遍历字典:
// 遍历字典的键值对
for (key, value) in dict {
    print("\(key): \(value)")
}

// 遍历字典的键
for key in dict.keys {
    print(key)
}

// 遍历字典的值
for value in dict.values {
    print(value)
}

这些只是字典操作的一部分,Swift 还提供了许多其他的字典操作方法和属性。详细内容可以参考 Swift 官方文档

swift 使用dic

原文地址: http://www.cveoy.top/t/topic/hGmE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录