文章目录
Swift 提供了三种主要的 集合类型,分别是数组、集合和字典,用于存储值集合。数组是有序的值集合。集合是无序的唯一值集合。字典是无序的键值对关联集合。

Swift 中的数组、集合和字典对于它们可以存储的值和键的类型始终是明确的。这意味着你不能错误地将一个类型不匹配的值插入到集合中。同时,这也意味着你可以放心地知道从集合中取出的值的类型。
※注意:
Swift 的数组、集合和字典类型是作为 泛型集合 实现的。 有关泛型类型和集合的更多信息,请参阅 泛型。
集合的可变性
如果您创建一个数组、集合或字典,并将其赋值给一个变量,则创建的集合将是 可变的。这意味着,在创建集合后,您可以通过添加、删除或更改集合中的元素来改变(或称为 变异)集合。如果您将数组、集合或字典分配给常量,则该集合是 不可变的,并且其大小和内容无法更改。
※注意:
在所有不需要更改的情况下,创建不可变集合是一种良好的实践。这样做可以使你更容易理解代码,并使 Swift 编译器能够优化你创建的集合的性能。
数组
数组——将相同类型的值存储在一个有序列表中。相同的值可以在数组中以不同位置多次出现。
※注意:
Swift 的 Array 类型与 Foundation 的 NSArray 类进行了桥接。 有关如何在 Foundation 和 Cocoa 中使用 Array 的更多信息,请参阅相关文档 Bridging Between Array and NSArray。
数组类型简写语法
Swift 数组的类型完整写作 Array<Element>,其中 Element 是数组允许存储的值的类型。你也可以以简写形式 [Element] 来表示数组的类型。虽然这两种形式在功能上是相同的,但简写形式更受欢迎,并且在本指南中提到数组类型时将优先使用这种形式。
创建空数组
您可以使用构造器语法创建某种类型的空数组:
var someInts: [Int] = []
print("someInts is of type [Int] with \(someInts.count) items.")
// 打印 “someInts is of type [Int] with 0 items.“
请注意,someInts 变量的类型根据初始化器的类型推断为 [Int]。
或者,如果上下文已经提供了类型信息,例如函数参数或已经定义类型的变量或常量,你可以使用空数组字面量 [](一对空的方括号)来创建一个空数组:
someInts.append(3)
// someInts 现在包含 1 个类型为 Int 的值
someInts = []
// someInts 现在是一个空数组, 但它仍是 [Int] 类型的
使用默认值创建数组
Swift 的 Array 类型还提供了一个构造器,用于创建特定大小的数组,其所有值都设置为相同的默认值。您向此构造器传递适当类型的默认值(称为 repeating):以及该值在新数组中重复的次数(称为 count):
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles 的类型是 [Double],并且等于 [0.0, 0.0, 0.0]
通过合并两个数组创建一个新数组
您可以通过使用加法运算符 (+) 将两个具有兼容类型的现有数组相加来创建新数组。新数组的类型是从您相加的两个数组的类型推断出来的:
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles 的类型是 [Double],并且等于 [2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles 被推断为 [Double] 类型,并且等于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
使用数组字面量创建数组
您还可以使用 数组字面量 来初始化数组,这是将一个或多个值写入数组集合的简写方法。数组字面量以值列表的形式写入,用逗号分隔,用一对方括号括起来:
[<#value 1#>, <#value 2#>, <#value 3#>]
下面的示例创建了一个名为 shoppingList 的数组来存储 String 值:
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList 已经用两个初始项进行了初始化
shoppingList 变量被声明为“字符串值数组”,写作 [String]。由于该数组指定了值类型为 String,因此它只允许存储 String 类型的值。在这里,shoppingList 数组通过数组字面量初始化了两个 String 值(“Eggs” 和 “Milk”)。
※注意:
shoppingList 数组被声明为变量(使用 var 关键字)而不是常量(使用 let 关键字),因为在下面的示例中,更多的商品要被添加到购物清单中。
在这个例子中,数组字面量只包含两个 String 值,且没有其他内容。这与 shoppingList 变量的声明类型(一个只能包含 String 值的数组)相匹配,因此允许使用这个数组字面量来初始化 shoppingList,并包含两个初始项目。
得益于 Swift 的类型推断功能,如果您使用包含相同类型值的数组字面量进行初始化,则无需显式地写出数组的类型。shoppingList 的初始化可以改为以更简短的形式编写:
var shoppingList = ["Eggs", "Milk"]
由于数组字面量中的所有值都是相同类型,Swift 可以推断出 [String] 是 shoppingList 变量的正确类型。
访问数组
您可以通过数组的方法和属性或使用下标语法来访问和修改数组。
count 属性
要找出数组中的项数,可以检查其只读属性 count:
print("The shopping list contains \(shoppingList.count) items.")
// 打印 “The shopping list contains 2 items.“
isEmpty 属性
使用布尔值 isEmpty 属性作为检查 count 属性是否等于 0 的快捷方式:
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list isn't empty.")
}
// 打印 “The shopping list isn't empty.“
first 和 last 用法
first:返回数组第一个元素(optional),如果数组为空,返回 nil 。last:返回数组最后一个元素(optional),如果数组为空,返回 nil 。first(where:):返回数组第一个符合给定条件的元素(optional)。last(where:):返回数组最后一个符合给定条件的元素(optional)。
var firstIndexItem = shoppingList.first ?? ""
print("firstIndexItem:\(firstIndexItem)")
var endIndexItem = shoppingList.last ?? ""
print("endIndexItem:\(endIndexItem)")
//满足条件的第一个元素
firstIndexItem = shoppingList.first(where: {$0.hasPrefix("M")}) ?? ""
print("firstIndexItem:\(firstIndexItem)")
//满足条件的最后一个元素
endIndexItem = shoppingList.last(where: {$0.hasSuffix("r")}) ?? ""
print("endIndexItem:\(endIndexItem)")
上述代码输出的结果为
firstIndexItem:Six eggs
endIndexItem:Bananas
firstIndexItem:Milk
endIndexItem:Baking Powder
获取数组中最大最小元素
min():返回数组中最小的元素max():返回数组中最大的元素
var arrayInt: [Int] = [0, 1, 2, 3, 4]
let maxItem = arrayInt.max()!
print("maxItem:\(maxItem)")
let minItem = arrayInt.min()!
print("minItem:\(minItem)")
上述代码输出结果为:
maxItem:4
minItem:0
修改数组
添加元素
您可以通过调用数组的 append(_:) 方法将新元素添加到数组的末尾:
shoppingList.append("Flour")
// shoppingList 现在包含 3 项,而有人正在做煎饼
或者,可以使用加法赋值运算符(+=)将一个或多个兼容项的数组追加到现有数组中:
shoppingList += ["Baking Powder"]
// shoppingList 现在包含 4 项
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList 现在包含 7 项
要将项目插入数组中指定索引处,请调用数组的 insert(_:at:) 方法:
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList 现在包含 7 项, ["Maple Syrup", "Six eggs", "Milk", "Flour", "Baking Powder", "Bananas", "Apples"]
// ”Maple Syrup“ 现在是列表中的第一项
对 insert(_:at:) 方法的调用会在购物清单的最开头插入一个值为 “Maple Syrup” 的新项目,由索引 0 表示。
修改元素
使用 下标语法 从数组中检索值,在数组名称后面的方括号[]内传递要检索的值的索引:
var firstItem = shoppingList[0]
// firstItem 的值为 “Eggs”
※注意:
数组中的第一项的索引为 0,而不是 1。Swift 中的数组始终是零索引的。
您可以使用下标语法来更改给定索引处的现有值:
shoppingList[0] = "Six eggs"
// 列表中的第一个项现在是 “Six eggs” 而不是 “Eggs”
当您使用下标语法时,您指定的索引需要有效。例如,编写 shoppingList[shoppingList.count] = “Salt” 以尝试将项目追加到数组末尾会导致运行时错误。
您还可以使用下标语法一次更改一个范围的值,即使替换值集的长度与要替换的范围不同。以下示例将 “Chocolate Spread”, “Cheese” 和 “Butter” 替换为 “Bananas” 和 “Apples”:
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList 现在包含 6 项 ["Six eggs", "Milk", "Flour", "Baking Powder", "Bananas", "Apples"]
删除元素
使用 remove(at:) 方法从数组中删除项目。此方法删除指定索引处的项目并返回已删除的项目(如果您不需要,可以忽略返回的值):
let mapleSyrup = shoppingList.remove(at: 0)
print("mapleSyrup:\(mapleSyrup) - shoppingList8:\(shoppingList)")
// 索引 0 处的项刚刚被移除了
// shoppingList 现在包含 6 项,且不包含 Maple Syrup
// mapleSyrup 常量现在等于已移除的 “Maple Syrup” 字符串
// 输出结果:mapleSyrup:Maple Syrup - shoppingList8:["Six eggs", "Milk", "Flour", "Baking Powder", "Bananas", "Apples"]
※注意:
如果您尝试访问或修改超出数组现有边界的索引的值,将触发运行时错误。您可以在使用索引之前通过将其与数组的 count 属性进行比较来检查索引是否有效。数组中最大的有效索引是count - 1,因为数组是从零开始编制索引的,—但是,当 count 为 0(意味着数组为空)时,没有有效的索引。
如果要从数组中删除最后一项,请使用 removeLast() 方法而不是 remove(at:) 方法,以避免查询数组的 count 属性。与 remove(at:) 方法一样,removeLast() 返回已删除的项目:
let apples = shoppingList.removeLast()
print("apples:\(apples) - shoppingList9:\(shoppingList)")
// 数组中的最后一项刚刚被移除了
// shoppingList 现在包含 5 项,且不包含 apples
// apples 常量现在等于已移除的 “Apples” 字符串
// 输出结果:apples:Apples - shoppingList9:["Six eggs", "Milk", "Flour", "Baking Powder", "Bananas"]
数组倒序
reverse():在原数组上将数组逆序,只能作用在数组变量上。reversed():返回原数组的逆序“集合表示”,可以作用在数组变量和常量上,该方法不会分配新内存空间。
var arrayInt: [Int] = [0, 1, 2, 3, 4]
arrayInt.reverse()
print("arrayInt:\(arrayInt)")
let newArrayInt = Array(arrayInt.reversed())
print("arrayInt:\(arrayInt)")
print("newArrayInt:\(newArrayInt)")
上述代码结果如下:
arrayInt:[4, 3, 2, 1, 0]
arrayInt:[4, 3, 2, 1, 0]
newArrayInt:[0, 1, 2, 3, 4]
随机打乱数组顺序
let arrayIntShu = [Int](0...20)
var arrIntShuff = arrayIntShu.shuffled()
print(arrIntShuff)
上述代码输出结果:
[10, 8, 9, 7, 2, 3, 0, 1, 11, 4, 16, 17, 15, 14, 6, 19, 5, 12, 20, 18, 13]
数组排序
sort():在原数组上将元素排序,只能作用于数组变量。sorted():返回原数组的排序结果数组,可以作用在数组变量和常量上。
arrIntShuff.sort()
print("arrIntShuff - sort:\(arrIntShuff)")
arrIntShuff = arrayIntShu.shuffled()
arrIntShuff.sort(by: {$0 > $1})
print("arrIntShuff - sortBy:\(arrIntShuff)")
arrIntShuff = arrayIntShu.shuffled()
var arrIntSorted = arrIntShuff.sorted()
print("arrIntShuff - sorted:\(arrIntSorted)")
arrIntShuff = arrayIntShu.shuffled()
arrIntSorted = arrIntShuff.sorted(by: {$0 > $1})
print("arrIntShuff - sortedBy:\(arrIntSorted)")
上述代码输出结果:
arrIntShuff - sort:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
arrIntShuff - sortBy:[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
arrIntShuff - sorted:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
arrIntShuff - sortedBy:[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
数组分组
partition(by belongsInSecondPartition: (Element) throws -> Bool) 将数组以某个 条件分组,数组前半部分都是不符合条件的元素,数组后半部分都是符合条件的元素。
arrIntShuff = arrayIntShu.shuffled()
print("arrIntShuff:\(arrIntShuff)")
let indexPartition = arrIntShuff.partition(by: {$0 > 6})
print("indexPartition:\(indexPartition)")
let partition1 = arrIntShuff[..<indexPartition]
let partition2 = arrIntShuff[indexPartition...]
print("partition1:\(partition1)")
print("partition2:\(partition2)")
上述代码输出结果:
arrIntShuff:[18, 8, 9, 16, 15, 5, 0, 20, 13, 3, 2, 19, 4, 7, 17, 1, 10, 12, 6, 14, 11]
indexPartition:7
partition1:[6, 1, 4, 2, 3, 5, 0]
partition2:[20, 13, 15, 16, 19, 9, 7, 17, 8, 10, 12, 18, 14, 11]
数组元素交换位置
swapAt(_:_:) 交换指定位置的两个元素。
var arrSwat = [Int](0...10)
arrSwat.swapAt(1, 5)
print("arrSwat:\(arrSwat)")
arrSwat.swapAt(arrSwat.startIndex, arrSwat.endIndex - 1)
print("arrSwat:\(arrSwat)")
上述代码输出结果:
arrSwat:[0, 5, 2, 3, 4, 1, 6, 7, 8, 9, 10]
arrSwat:[10, 5, 2, 3, 4, 1, 6, 7, 8, 9, 0]
遍历数组
for-in遍历
您可以使用 for-in 循环遍历数组中整个的值的集合:
for item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
如果你需要每个项目的整数索引及其值,请使用 enumerated() 方法遍历数组。对于数组中的每个元素,enumerated() 方法返回一个由整数和项组成的元组。整数从 0 开始,每个项目按 1 计数;如果枚举整个数组,则这些整数将与这元素的索引匹配。您可以将这些元组分解为临时常量或变量,作为遍历的一部分:
for (index, value) in shoppingList.enumerated() {
print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
for-each遍历
shoppingList.forEach { item in
if item == "Milk" {
return
}
print("forEach - item:\(item)")
}
//forEach - item:Six eggs
//forEach - item:Flour
//forEach - item:Baking Powder
//forEach - item:Bananas
69



被折叠的 条评论
为什么被折叠?



