Swift语言提供数组
(Array)、集合
(Set)和字典
(Dictionary)三种基本的集合类型用来存储集合数据。数组是有序数据的集。集合是无序无重复数据的集。字典是无序的键值对的集。

1、数组
(1)数组的简单语法
Swift中数组的完整写法为:Array<Element>
或者 Array[Element]
.
(2)创建数组
- 创建空数组
var someInts = [Int]()
var someInts: [Int] = []
- 创建带有默认值的数组
var threeDoubles = Array(repeating: 0.0, count: 3)
- 通过两个数组相加创建一个数组
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
var sixDoubles = threeDoubles + anotherThreeDoubles
- 用数组字面量构造数组
var shoppingList: [String] = ["Eggs", "Milk"]
(3)访问和修改数组
- 使用
count
属性获取数组中的数据项数量
print("The shopping list contains \(shoppingList.count) items.")
- 使用布尔属性
isEmpty
检查count
属性是否为0
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
- 使用
append(_:)
方法在数组后面添加新元素
shoppingList.append("Flour")
- 使用
+=
直接将另一个相同类型数组中的元素添加到该数组后面
shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
- 使用下标语法获取数组中的元素
var firstItem = shoppingList[0]
- 可以用下标来改变某个有效索引值对应的元素值
shoppingList[0] = ["Six eggs"]
- 可以利用下标来一次改变一系列数据值,即使新数据和原有数据的数量是不一样的
shoppingList[4...6] = ["Bananas", "Apples"]
- 调用数组的
insert(_:at:)
方法在某个指定索引值之前添加数据项
shoppingList.insert("Maple syrup", at: 0)
- 使用
remove(at:)
方法来移除数组中的某一项
let mapleSyrup = shoppingList.remove(at: 0)
- 移除数组中的最后一项元素
let apples = shoppingList.removeLast()
(4)数组的遍历
- 使用
for-in
循环来遍历数组中所有的元素:
for item in shoppingList {
print(item)
}
//Six eggs
//Milk
//Flour
//Baking Powder
//Bananas
- 如果同时需要每个数据项的值和索引值,可以使用
enumerated()
方法来进行数组遍历。enumerated()
返回一个由索引值和数据值组成的元组数组。
for (index, value) in shoppingList.enumerated() {
print("Item \(String(index + 1)): \(value)")
}
//Item 1: Six eggs
//Item 2: Milk
//Item 3:Flour
//Item 4: Baking Powder
//Item 5: Bananas
2、集合
集合用来存储相同类型并且没有确定顺序的值。当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组。集合三个特性:
- a == a (自反性)
- a== b 意味着 b == a(对称性)
- a == b && b == c 意味着 a == c (传递性)
(1)集合类型语法
Swift 中的集合类型被写为 Set<Element>
(2)创建集合
- 通过构造器语法创建一个特定类型的空集合:
var letters = Set<Character>()
- 如果上下文提供了类型信息,那么可以通过一个空的数组字面量创建一个空的集合:
letters = [] //letters现在是一个空的Set,但是它依然是 Set<Character>类型
- 用数组字面量创建集合
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
(3)访问和修改集合
- 可以使用
count
属性来获取集合中元素的数量:
print("I have \(favoriteGenres.count) favorite music genres.")
- 使用布尔属性
isEmpty
作为一个缩写形式去检查count
属性是否为0
if favoriteGenres.isEmpty {
print("As far as music goes, I'm not picky.")
} else {
print("I have particular music preferences.")
}
- 通过调用集合的
insert(_:)
方法来添加一个新元素
favoriteGenres.insert("Jazz")
- 通过调用集合的
remove(_:)
方法去删除一个元素,如果它是该集合的一个元素则删除它并且返回它的值,若该集合不包含它,则返回 nil
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
- 可以通过
removeAll()
方法删除所有元素 - 使用
contains(_:)
方法去检查集合中是否包含一个特定的值
if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
}
(4)集合的遍历
- 可以在一个
for-in
循环中遍历一个集合中的所有值
for genre in favoriteGenres {
print("\(genre)")
}
//Classical
//Jazz
//Hip hop
- Swift 的
Set
类型没有确定的顺序,为了按照特定顺序来遍历一个集合中的值可以使用sorted()
方法,它将返回一个有序数组,这个数组的元素排列顺序由操作符<
对元素进行比较的结果来确定。
for genre in favoriteGenres.sorted() {
print("\(genre)")
}
//Classical
//Jazz
//Hip hop
(5)集合操作
1)基本集合操作
下面的插图描述了两个集合 a
和b
,以及通过阴影部分的区域显示集合各种操作的结果。

- 使用
intersection(_:)
方法根据两个集合的交集创建一个新的集合。 - 使用
symmetricDifference(_:)
方法根据两个集合不相交的值创建一个新的集合。 - 使用
union(_:)
方法根据两个集合的所有值创建一个新的集合。 - 使用
subtracting(_:)
方法根据不在另一个集合中的值创建一个新的集合。
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.interaction(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
2)集合成员关系和相等
下面的插图描述了三个集合 a
、b
和 c
,以及通过重叠区域表述集合间共享的元素。集合a
是集合 b
的父集合,因为 a
包含了 b
中所有的元素。相反的,集合 b
是集合 a
的子集合,因为属于 b
的元素也被 a
包含。集合 b
和集合 c
是不相交的,因为它们之间没有共同的元素。

- 使用“是否相等”运算符(
==
)来判断两个集合包含的值是否全部相同。 - 使用
isSubset(of:)
方法来判断一个集合中的所有值是否也被包含在另外一个集合中。 - 使用
isSuperset(of:)
方法来判断一个集合是否包含另一个集合中所有的值。 - 使用
isStrictSubset(of:)
或者isStrictSuperset(of:)
方法来判断一个集合是否是另外一个集合的子集合或者父集合并且两个集合并不相等。 - 使用
isDisjoint(with:)
方法来判断两个集合是否不含有相同的值(是否没有交集)
let houseAnimals: Set = ["", ""]
let farmAnimals: Set = ["", "", "", "", ""]
let cityAnimals: Set = ["", ""]
houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true
3、字典
(1)字典类型简化语法
Swift 的字典使用 Dictionary<Key, Value>
定义,其中 Key
是一种可以在字典中被用作键的类型,Value
是字典中对应于这些键所存储值的数据类型。也可以用 [Key: Value]
这样简化的形式去表示字典类型。
(2)创建字典
- 可以像数组一样使用构造语法创建一个拥有确定类型的空字典
var namesOfIntegers = [Int: String]()
// namesOfIntegers 是一个空的 [Int: String] 字典
- 如果上下文已经提供了类型信息,可以使用空字典字面量来创建一个空字典,记作
[:]
namesOfIntegers[16] = "sixteen"
//namesOfIntegers 现在包含一个键值对
namesOfIntegers = [:]
// nameOfIntegers 又成为了一个 [Int: String] 类型的空字典
- 用字典字面量创建字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
//如果键和值都有各自统一的类型,可以不必写出字典的类型
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
(3)访问和修改字典
- 可以通过
Dictionary
的只读属性count
来获取字典的数据项数量:
print("The dictionary of airports contains \(airports.count) items.")
- 使用布尔属性
isEmpty
作为一个缩写形式去检查count
属性是否为0
:
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}
- 可以通过下标语法来给字典添加新的数据项。
airports["LHR"] = "London"
// airports 字典现在有三个数据项
- 也可以使用下标语法来改变特定键对应的值
airports["LHR"] = "London Heathrow"
// "LHR" 对应的值被改为 “London Heathrow”
- 作为一种替代下标语法的方式,字典的
updateValue(_:forKey:)
方法可以设置或者更新特定键对应的值。就像上面所示的下标示例,updateValue(_:forKey:)
方法在这个键不存在对应值的时候会设置新值或者在存在时更新已存在的值。和下标的方式不同,updateValue(_:forKey:)
这个方法返回更新值之前的原值(可选类型)。这样使得你可以检查更新是否成功。
if let oldValue = airports.updateValue("Dublin Airport", forKey:"DUB") {
print("The old value for DUB was \(oldValue).")
}
// 输出 “The old value for DUB was Dublin.”
- 可以使用下标语法来在字典中检索特定键对应的值,返回对应值类型的可选类型。
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
//打印 “The name of the airport is Dublin Airport.”
- 可以使用下标语法通过将某个键的对应值赋值为 nil 来从字典里移除一个键值对
airports["APL"] = "Apple Internation"
airports["APL"] = nil
-
removeValue(forKey:)
方法也可以用来在字典中移除键值对。这个方法在键值对存在的情况下会移除该键值对并且返回被移除的值或者在没有对应值的情况下返回nil
if let removedValue = airports.removeValue(forKey: "DUB") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary does not contain a value for DUB.")
}
// 打印“The removed airport's name is Dublin Airport.”
(4)字典遍历
- 使用
for-in
遍历,每个字典中的数据项都以(key, value)
元组形式返回
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
- 通过访问
keys
或者values
属性,你也可以遍历字典的键或者值:
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR
for airportName in airports.values {
print("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow
- 可以直接使用
keys
或者values
属性构造一个新数组:
let airportCodes = [String](airports.keys)
let airportName = [String](airports.values)
Swift 的 Dictionary
是无序集合类型。为了以特定的顺序遍历字典的键或值,可以对字典的 keys
或 values
属性使用 sorted()
方法。
网友评论