返回

集合入门:Swift 数组、集合和字典指南

IOS

集合概述

在 Swift 中,集合是一种可以存储一组值的数据结构。集合有三种主要类型:数组、集合和字典。

  • 数组 是有序的值集合。数组中的值按照它们被添加的顺序存储。您可以使用下标访问数组中的值,下标是从 0 开始的整数。
  • 集合 是唯一值的无序集合。集合中的值没有特定的顺序。您可以使用插入、删除和查找操作来修改集合。
  • 字典 是键值对的集合。字典中的键是唯一的,并且每个键都与一个值相关联。您可以使用键来访问字典中的值。

数组

数组是 Swift 中最常用的集合类型。数组是有序的值集合,您可以使用下标访问数组中的值。

var myArray = [1, 2, 3, 4, 5]

print(myArray[0]) // 输出 1
print(myArray[2]) // 输出 3
print(myArray[4]) // 输出 5

您还可以使用 append() 方法向数组中添加值,并使用 remove() 方法从数组中删除值。

myArray.append(6) // 将 6 添加到数组末尾

myArray.remove(at: 2) // 从数组中删除索引为 2 的元素

print(myArray) // 输出 [1, 2, 4, 5, 6]

集合

集合是唯一值的无序集合。您可以使用插入、删除和查找操作来修改集合。

var mySet = Set<Int>()

mySet.insert(1)
mySet.insert(2)
mySet.insert(3)
mySet.insert(4)
mySet.insert(5)

print(mySet) // 输出 [1, 2, 3, 4, 5]

您可以使用 contains() 方法来检查集合中是否包含某个值。

print(mySet.contains(3)) // 输出 true
print(mySet.contains(6)) // 输出 false

字典

字典是键值对的集合。字典中的键是唯一的,并且每个键都与一个值相关联。您可以使用键来访问字典中的值。

var myDictionary = [String: Int]()

myDictionary["one"] = 1
myDictionary["two"] = 2
myDictionary["three"] = 3

print(myDictionary["one"]) // 输出 1
print(myDictionary["two"]) // 输出 2
print(myDictionary["three"]) // 输出 3

您可以使用 updateValue() 方法来更新字典中的值,并使用 removeValue() 方法从字典中删除值。

myDictionary.updateValue(4, forKey: "one")

myDictionary.removeValue(forKey: "two")

print(myDictionary) // 输出 ["one": 4, "three": 3]

结论

数组、集合和字典是 Swift 中三种最常用的集合类型。这些集合类型可以用来存储各种各样的数据,并且可以有效地组织和管理数据。