0Pricing
Swift Academy · 课时

集合

集合

集合 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 1 节课,共 1 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 1 节课。

简介

您好,

本课将学习 Swift 中的集合类型,这是最重要的主题之一。

那么,让我们开始吧。

Swift 中有 3 种集合类型。

数组 → 有序集合类型。

集合 → 无序且不重复的集合类型。

字典 → 无序的键值对集合类型。

不可变 - 可变

集合类型是不可变还是可变,取决于我们的定义方式。

如果使用 let 语句定义,它就是不可变的;如果使用 var 定义,它就是可变的。

如果定义的值之后不会改变,使用 let 可以让编译器更好地进行优化,从而提升性能。

数组

数组

数组是用于按顺序保存数据的集合类型。从 Swift 3 版本开始,数组中的所有元素不必属于同一种类型。

下面的示例展示了简单数组定义的语法。

// Let's create an empty array.
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."

使用默认值创建数组

使用默认值创建数组

在某些情况下,我们可能希望创建一个具有默认值和特定大小的数组。为此,我们需要向数组构造器传入两个参数。

这些参数用于指定默认值以及数组包含的元素数量。

var threeDoubles = Array(repeating: 0.0, count: 3)
print(threeDoubles)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]
print(anotherThreeDoubles)

var sixDoubles = threeDoubles + anotherThreeDoubles
print(sixDoubles)
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

使用数组字面量创建数组

使用数组字面量创建数组

在前面的示例中,我们学习了如何创建空数组。不过,在某些情况下,我们可能希望使用数组字面量创建数组。

让我们通过示例学习它的用法。

/*
We have defined a variable named catList, 
and with the [String] statement we specified 
that its type is an Array containing String elements.
*/
var catList: [String] = ["Garfield", "Tom"]
print(catList)
/*
It will understand that the array is an Array containing
String statements, since we assign a value that 
defines the variable. (Swift type inference)
*/
var shoppingList = ["Eggs", "Milk"]
print(shoppingList)

访问数组值

访问数组的值

如果要访问序列中特定索引处的元素,只需使用以下语法调用它即可。

myArray [index]

让我们来看一下示例。

// We have defined an array with 3 elements of type Int.
var numbers:[Int] = [1, 5, 21]

// Arrays start from Index 0. For example, in order to reach the value 5, which is the 2nd element, we need to access the 1st index.
var a = numbers[1]
print( "Value of numbers at index 1 is \(a)" )

向数组添加新元素

向数组添加新元素

我们可以向数组添加新项。 

在下面的示例中,定义了一个名为 catList 的数组。接下来,使用 append 方法向该数组添加了一个新项。 

// The Array named catList was defined with 1 initial element.
var catList = ["Tom"]


/*
We are adding a new item with a Garfield 
value using the append method.
*/
catList.append("Garfield")
// Our array will now have 2 elements.


/*
With the + = operator, we can do the 
work that the append method does.
*/
catList += ["Sylvester"]

向数组中的指定索引添加数据

向数组中的指定索引添加数据

在前面的示例中,使用 append 方法添加的值会被添加到数组末尾。不过,有时我们可能希望将其添加到指定索引处。这时可以使用 insert 方法。

语法如下所示。

myArr.insert ("The data to add", at: index);

让我们通过示例来了解它。

var catList = ["Tom"]

catList.insert("Garfield", at: 1)

print(catList)

删除数组中的指定元素

删除数组中的指定元素

remove 方法用于删除数组中指定索引处的元素。

var shoppingList = ["Apple", "Cherry", "Cheese"]

let shoppingListOne = shoppingList.remove(at: 0)
// the item that was at index 0 has just been removed
// the mapleSyrup constant is now equal to the removed "Maple Syrup" string

let shoppingListTwo = shoppingList.removeLast()
// the last item in the array has just been removed

print(shoppingListTwo)

数组遍历

我们可以使用 for-in 语句遍历已有的数组。

让我们来看一个示例。

var shoppingList = ["Banana", "Orange", "Milk"]

for item in shoppingList {
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas

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

集合

集合

用于将相同类型的元素无序地集合在一起。

顾名思义,它们是集合。集合中不能有两个值相同的元素。

创建空集合

我们使用下面的示例创建一个空集合。

var catSet = Set<Character>()

使用数组字面量创建集合

使用数组字面量创建集合

可以使用数组字面量创建集合。请注意,虽然这里赋的值看起来像数组,但变量的类型是字符串集合。

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

警告

使用数组字面量时,如果不定义类型,就无法创建集合。这可能会与数组混淆。因此,我们需要定义类型。 

至少应按下面的方式使用它。

var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

集合方法

集合方法

让我们来看一个示例

var favoriteGenres = ["Funk"]

print("I have \(favoriteGenres.count) favorite music genres.")

if favoriteGenres.isEmpty {
    print("favoriteGenres is empty")
} else {
    print("I have particular music preferences.")
}

if favoriteGenres.contains("Funk") {
    print("Funk")
} 

遍历集合

遍历集合

Swift 的集合类型没有顺序。不过,在遍历集合值时可以使用 sorted 方法。此方法会将集合元素整理成数组。

let favoriteGenres = ["Classical","Jazz", "Hip hop"]

for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop

字典

字典

字典是以键值对保存值的集合类型,不包含任何顺序。

每个值都通过唯一的键保存。这个键表示该值在字典中的 ID。字典不像数组那样包含固定的顺序。我们可以把它想象成现实世界中的字典。

因此,每个值的标识比排列顺序更重要。

字典类型可以通过简写类型 [键: 值] 进行定义。更推荐使用简写形式。

var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

字典访问方法

我们可以通过计数方法了解字典包含多少个元素。

此外,我们还可以通过 isEmpty 方法检查字典是否为空。

让我们通过一些示例来了解这些方法。

var airports = ["LHR": "London", "IST": "Istanbul"]

print("The airports dictionary contains \(airports.count) items.")
// Prints "The airports dictionary contains 2 items."

if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// Prints "The airports dictionary is not empty."

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

下标

使用下标获取值的过程如下。返回结果是可选值。

var airports = ["DUB":"Dublin"]

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// Prints "The name of the airport is Dublin Airport."



//Deletion
airports["APL"] = 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.")
}
// Prints "The removed airport's name is Dublin Airport."

更新字典

除了使用上面的下标方式外,还可以使用一种方法来更新字典。

此方法的特点是,更新完成后会返回更新前的旧值。

var airports = ["DUB": "Dublin"]

if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}
// Prints "The old value for DUB was Dublin."

下面是将字典转换为数组的示例

下面是将字典转换为数组的示例。


let airports = ["IST":"Istanbul Airport", "DUB":"Dublin Airport"]

let airportCodes = [String](airports.keys)
print(airportCodes)

let airportNames = [String](airports.values)
print(airportNames)

恭喜您

恭喜您 🎉

本课中,我们学习了如何在 Swift 中使用集合。

下一课再见。

集合 — 插图 22

常见问题解答

「集合」课时是免费的吗?

是的 — 「集合」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 1 节课。

「集合」这节课中我会学到什么?

集合 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Swift Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 1 节。

「集合」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Swift Academy 课中编写并运行代码吗?

能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

← 返回 Swift Academy