Swift 数组(Array)、集合(Set)和字典(Dictionary) 的代码示范

50 min read

数组 (Array)

// 定义一个空数组,用于存储字符串类型的数据
var stringArray = [String]()

// 添加数据到数组
stringArray.append("apple")
stringArray.append("banana")
stringArray.append("orange")

// 访问数组中的元素
print(stringArray[0]) // 输出 "apple"

// 遍历数组中的元素
for fruit in stringArray {
    print(fruit)
}

// 定义一个带初始值的数组
var numberArray = [1, 2, 3, 4, 5]

// 获取数组的长度
print(numberArray.count) // 输出 5

// 修改数组的元素
numberArray[0] = 10

// 删除数组中的元素
numberArray.remove(at: 3)

// 数组排序
numberArray.sort()

集合(Set)

// 定义一个空集合,用于存储字符串类型的数据
var stringSet = Set<String>()

// 添加数据到集合
stringSet.insert("red")
stringSet.insert("green")
stringSet.insert("yellow")

// 访问集合中的元素
print(stringSet.contains("red")) // 输出 true

// 遍历集合中的元素
for color in stringSet {
    print(color)
}

// 定义一个带初始值的集合
var numberSet: Set = [1, 2, 3, 4, 5]

// 获取集合的长度
print(numberSet.count) // 输出 5

// 删除集合中的元素
numberSet.remove(3)

// 集合操作
let set1: Set = [1, 2, 3]
let set2: Set = [3, 4, 5]
let unionSet = set1.union(set2) // 并集 {1, 2, 3, 4, 5}
let interSectionSet = set1.intersection(set2) // 交集 {3}
let subtractingSet = set1.subtracting(set2) // 差集 {1, 2}

字典(Dictionary)

// 定义一个空字典,用于存储键为字符串类型、值为整型的数据
var intDictionary = [String: Int]()

// 添加数据到字典
intDictionary["apple"] = 2
intDictionary["banana"] = 3
intDictionary["orange"] = 4

// 访问字典中的元素
print(intDictionary["apple"]) // 输出 Optional(2)

// 遍历字典中的键值对
for (fruit, count) in intDictionary {
    print("\(fruit)\(count)个")
}

// 定义一个带初始值的字典
var stringDictionary = [
    "name": "Tom",
    "age": "18"
]

// 获取字典的长度
print(stringDictionary.count) // 输出 2

// 修改字典中的元素
stringDictionary["age"] = "19"

// 删除字典中的元素
stringDictionary.removeValue(forKey: "age")