Swift 字典

Swift 字典是无序的元素集合。它以键/值对的形式存储元素。在这里,是与每个关联的唯一标识符。

让我们看一个例子。

如果我们想存储有关国家及其首都的信息,我们可以创建一个以国家名称作为、首都作为的字典。

尼泊尔 加德满都
意大利 罗马
英格兰 伦敦

在 Swift 中创建字典

以下是在 Swift 中创建字典的方法。

var capitalCity = ["Nepal": "Kathmandu", "Italy": "Rome", "England": "London"]
print(capitalCity)

输出

["Nepal": "Kathmandu", "England": "London", "Italy": "Rome"]

在上面的示例中,我们创建了一个名为 capitalCity 的字典。这里,

  • "Nepal""Italy""England"
  • "Kathmandu""Rome""London"

当我们运行此代码时,输出的顺序可能不同。这是因为字典没有特定的顺序。

注意: 这里,键和值都为 String 类型。我们也可以使用不同数据类型的键和值。


示例:Swift 字典

// dictionary with keys and values of different data types
var numbers = [1: "One", 2: "Two", 3: "Three"]
print(numbers)

输出

[3: "Three", 1: "One", 2: "Two"]

在上面的示例中,我们创建了一个名为 numbers 的字典。这里,Int 类型,String 类型。


向字典添加元素

我们可以使用字典名称和 [] 来向字典添加元素。例如,

var capitalCity = ["Nepal": "Kathmandu", "England": "London"]
print("Initial Dictionary: ",capitalCity)

capitalCity["Japan"] = "Tokyo"

print("Updated Dictionary: ",capitalCity)
print(capitalCity["Japan"])

输出

Initial Dictionary:  ["Nepal": "Kathmandu", "England": "London"]
Updated Dictionary:  ["Nepal": "Kathmandu", "England": "London", "Japan": "Tokyo"]

在上面的示例中,我们创建了一个名为 capitalCity 的字典。请注意这一行:

capitalCity["Japan"] = "Tokyo"

在这里,我们向 capitalCity 添加了一个新元素,其JapanTokyo


更改字典的值

我们也可以使用 [] 来更改与特定键关联的值。例如,

var studentID = [111: "Eric", 112: "Kyle", 113: "Butters"]
print("Initial Dictionary: ", studentID)

studentID[112] = "Stan"

print("Updated Dictionary: ", studentID)

输出

Initial Dictionary:  [111: "Eric", 113: "Butters", 112: "Kyle"]
Updated Dictionary:  [111: "Eric", 113: "Butters", 112: "Stan"]

在上面的示例中,我们创建了一个名为 studentID 的字典。最初,与 112 相关的值是 "Kyle"。现在,请注意这一行:

studentID[112] = "Stan"

在这里,我们将与键 112 相关的值更改为 "Stan"


从字典访问元素

在 Swift 中,我们可以独立访问字典的键和值。

1. 仅访问键

我们使用 keys 属性来访问字典中的所有键。例如:

var cities = ["Nepal":"Kathmandu", "China":"Beijing", "Japan":"Tokyo"]

print("Dictionary: ", cities)

// cities.keys return all keys of cities
var countryName  = Array(cities.keys)

print("Keys: ", countryName)

输出

Dictionary:  ["Nepal": "Kathmandu", "Japan": "Tokyo", "China": "Beijing"]
Keys:  ["Nepal", "Japan", "China"]

2. 仅访问值

同样,我们使用 values 属性来访问字典中的所有值。例如:

var cities = ["Nepal":"Kathmandu", "China":"Beijing", "Japan":"Tokyo"]

print("Dictionary: ", cities)

// cities.values return all values of cities
var countryName  = Array(cities.values)

print("Values: ", countryName)

输出

Dictionary:  ["Nepal": "Kathmandu", "China": "Beijing", "Japan": "Tokyo"]
Values:  ["Kathmandu", "Beijing", "Tokyo"]

从字典中删除元素

我们使用 removeValue() 方法从字典中删除元素。例如:

var studentID = [111: "Eric", 112: "Kyle", 113: "Butters"]

print("Initial Dictionary: ", studentID)

var removedValue  = studentID.removeValue(forKey: 112)

print("Dictionary After removeValue(): ", studentID)

输出

Initial Dictionary:  [113: "Butters", 111: "Eric", 112: "Kyle"]
Dictionary After removeValue():  [111: "Eric", 113: "Butters"]

这里,我们创建了一个名为 studentID 的字典。请注意

var removedValue  = studentID.removeValue(forKey: 112)

removeValue() 方法删除与键 112 相关联的元素。

注意:我们也可以使用 removeAll() 函数来删除字典中的所有元素。


其他字典方法

方法 描述
sorted() 对字典元素进行排序
shuffled() 更改字典元素的顺序
contains() 检查指定的元素是否存在
randomElement() 从字典中返回一个随机元素
firstIndex() 返回指定元素的索引

遍历字典

我们使用 for 循环来遍历字典的元素。例如:

var classification = ["Fruit": "Apple", "Vegetable": "Broccoli", "Beverage": "Milk"]

print("Keys: Values")

for (key,value) in classification {
  print("\(key): \(value)")
}

输出

Keys: Values
Vegetable: Broccoli
Beverage: Milk
Fruit: Apple

查找字典元素数量

我们可以使用 count 属性来查找字典中存在的元素数量。例如:

var studentID = [111: "Eric", 112: "Kyle", 113: "Butters"]
print(studentID.count)

输出

3

创建空字典

在 Swift 中,我们也可以创建空字典。例如:

var emptyDictionary =  [Int: String]()
print("Empty Dictionary: ",emptyDictionary)

输出

Empty Dictionary:  [:]

在上面的示例中,我们创建了一个空字典。请注意表达式

[Int: String]()

这里,

  • Int 表示字典的键将是整数类型
  • String 表示字典的值将是 String 类型。

注意:在创建空字典时,必须指定字典的数据类型。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战