集合类型
数组
创建数组
- 你可以使用确定类型通过初始化器语法来创建一个空数组:
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// prints "someInts is of type [Int] with 0 items."
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// prints "someInts is of type [Int] with 0 items."
- 相反,如果内容已经提供了类型信息,比如说作为函数的实际参数或者已经分类了的变量或常量,你可以通过空数组字面量来创建一个空数组,它写作
[ ]
(一对空方括号):
someInts.append(3)
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]
- 使用默认值创建数组:
Swift
的Array
类型提供了初始化器来创建确定大小且元素都设定为相同默认值的数组。你可以传给初始化器对应类型的默认值(叫做repeating
)和新数组元素的数量(叫做count
):
var threeDoubles = Array(repeating: 0.0, count: 3)
// 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]
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
- 使用数组字面量创建数组:使用数组字面量来初始化一个数组,它是一种以数组集合来写一个或者多个值的简写方式。数组字面量写做一系列的值,用逗号分隔,用方括号括起来:
var shoppingList: [String] = ["Eggs", "Milk"]
var shoppingList = ["Eggs", "Milk"]
访问和修改数组
- 数组中元素的数量,检查只读的
count
属性:
var shoppingList = ["Eggs", "Milk"]
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.")
}
// prints "The shopping list is not empty."
- 通过
append(_:)
方法给数组末尾添加新的元素:
shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes
- 使用加赋值运算符
+=
来在数组末尾添加一个或者多个同类型元素:
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items
- 通过下标脚本语法来从数组当中取回一个值:
var firstItem = shoppingList[0]
- 使用下标脚本语法来改变给定索引中已经存在的值:
shoppingList[0] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs"
- 使用下标脚本语法来一次改变一个范围的值,就算替换与范围长度不同的值的合集也行。
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items
- 要把元素插入到特定的索引位置,调用数组的
insert(_:at:)
方法:
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list
- 使用
remove(at:)
方法来移除一个元素。这个方法移除特定索引的元素并且返回它(不需要的话可以无视返回的值):
let mapleSyrup = shoppingList.remove(at: 0)
// the item that was at index 0 has just been removed
// shoppingList now contains 6 items, and no Maple Syrup
// the mapleSyrup constant is now equal to the removed "Maple Syrup" string
- 移除数组最后一个元素,使用
removeLast()
方法
let apples = shoppingList.removeLast()
// the last item in the array has just been removed
// shoppingList now contains 5 items, and no apples
// the apples constant is now equal to the removed "Apples" string
遍历一个数组
- 你可以用
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 \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
字典
字典储存无序的互相关联的同一类型的键和同一类型的值的集合。
- 创建空字典
var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]
- 创建字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
- 使用布尔量 isEmpty属性作为检查 count属性是否等于 0的快捷方式:
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}
// prints "The airports dictionary is not empty."
- 使用 count只读属性来找出 Dictionary拥有多少元素:
print("The airports dictionary contains \(airports.count) items.")
- 使用布尔量 isEmpty属性作为检查 count属性是否等于 0的快捷方式:
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}
// prints "The airports dictionary is not empty."
- 用下标脚本给字典添加新元素或修改元素或使用字典的
updateValue(_:forKey:)
方法来设置或者更新特点键的值:
airports["LHR"] = "London"
// the airports dictionary now contains 3 items
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
- 使用
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.")
}
airports["APL"] = "Apple International"
// "Apple International" is not the real airport for APL, so delete it
airports["APL"] = nil
// APL has now been removed from the dictionary
- 用 for-in循环来遍历字典的键值对。字典中的每一个元素返回为
(key, value)
元组:
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
元组
一组元素。元素与元素之间一般有一些关联
let yz = (1, 2)
//
let yz1 = (1, 2, "a", "b")
yz1.0
yz1.2
//
let student: = (name: "wang", age: 18)