# 从零开始Swift之集合

### 数组的用法

#### 1. 创建一个空数组

``````var someInts = [Int]()
``````

==如果数组之前确定过类型,则即使使用字面量将其重新变为空数组,该数组也只能存以前确定过的类型==

``````someInts.append(3)

someInts = [];// 此时数组类型依旧是Int
``````

#### 2.通过默认值创建一个数组

``````var threeDoubles = Array(repeating: 0.0, count: 3)
// 此时数组中有三个值,(0.0,0.0,0.0)
``````

#### 3.通过两个数组拼接成一个数组

``````var threeDoubles = Array(repeating: 0.0, count: 3)

var otherThreeDoubles = Array(repeating: 2.5, count: 3)

var sixDoubles = threeDoubles + otherThreeDoubles

``````

#### 4. 通过字面量创建数组

``````var shopingList: [String] = ["牙膏","牙刷"]
``````

#### 5. count:数组中的元素

``````print("The shopping list contains \(shoppingList.count) items.")
// Prints "The shopping list contains 2 items.”
``````

#### 6 isEmpty :判断数组中是否有元素

``````“if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}”

``````

#### 7. append(_:) 在数组的最后面拼接

``````shoppingList.append("Flour")
``````

#### 8. +=

``````shopingList += ["沐浴露","洗发水"]

shopingList += ["保鲜膜","剃须刀"]
``````

#### 9. 取值,使用下标的方式

``````var firstItem = shopingList[0]
``````
##### 也可以通过下标改变一个值
``````shopingList[0] = "电池"
``````

#### 10. 通过下标的方式改变一个范围的值

``````shopingList[2...4] = ["浴巾","锅"]
``````

#### 11. 插入一个新元素

``````shopingList.insert("电脑", at: 0)
``````

#### 12. 移除一个元素

``````shopingList.remove(at: 0)
``````

#### 13. 移除最后一个元素可以使用removeLast(),removeLast()也可以返回移除的最后一个元素

``````let removeItem = shopingList.removeLast()
``````

#### 14. 遍历数组

##### 第一种
``````for item in shoppingList {
print(item)
}
``````
##### 第二种
``````for (index, value) in shoppingList.enumerated() {
print("Item \(index + 1): \(value)")
}
``````

### 初始化方法

#### 1. 创建一个空的Set

``````var letters = Set<Character>()
``````

==跟数组一样如果集合之前确定过类型,则即使使用字面量将其重新变为空集合,该集合也只能存以前确定过的类型==

``````letters.insert("a")

letters = []// 类型仍然为Character
``````

#### 2. 使用数组字面量的方式快速创建一个Set

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

#### 3. set不能值靠数组字面量来推理出类型,所以必须给定类型,但是由于Swift 自动推断的存在, 如果一个字面量数组中包含的所有元素都是一种的时候, 可以推断类型

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

### 使用和修改set, 通过属性和方法来使用和修改set

#### 1. 属性.count 只读属性,可以获取到元素个数

``````print("我有\(favoriteGenres.count)个喜欢音乐类型")
``````

#### 2. 属性isEmpty用来快速检查count是否为零的属性

``````if favoriteGenres.isEmpty {
print("我没有喜欢的音乐类型")
}else{
print("我有喜欢的音乐类型")
}
``````

#### 3. 方法remove(_:)移除某个元素,并且返回值,如果该元素不包含在set中,则返回nil

``````if let removeGenre = favoriteGenres.remove("Rock") {
print("\(removeGenre)? I'm over it")
}else{
print("I never much cared for that")
}
``````

#### 4. 方法 _insert 插入一个元素

``````favoriteGenres.insert("Jazz")
``````

#### 5. 方法 removeAll() 移除所有元素

``````favoriteGenres.removeAll()
``````

#### 6. 方法.contains set中是否包含某个值

``````if favoriteGenres.contains("Funk") {
print("favoriteGenres 中包含Funk")
}else{
print("favoriteGenres 中不包含Funk")
}
``````

### 遍历一个set

``````favoriteGenres = ["Rock", "Classical", "Hip hop"]
for genre in favoriteGenres {
print("\(genre)")
}
``````

#### 升序排序

``````for genre in favoriteGenres.sorted() {
print("\(genre)")
}
``````

### Set快速操作

#### 4. a.subtraction(b) 从集合a中去除集合b包含的元素

``````var setA: Set = ["a","b","c","d","e"]

var setB: Set = ["c","d","e","f","g"]

print("\(setA.intersection(setB))")

print("\(setA.symmetricDifference(setB))")

print("\(setA.union(setB))")

print("\(setA.subtracting(setB))")
``````

#### 7. isDisjoint 判断两个集合是否有公共部分

``````let houseAnimals: Set = ["🐶","🐱"]

let farmAnimals: Set = ["🐮","🐔","🐑","🐶","🐱"]

let cityAnimals: Set = ["🐦","🐭"]

houseAnimals.isSubset(of: farmAnimals)

farmAnimals.isSuperset(of: houseAnimals)

farmAnimals.isDisjoint(with: cityAnimals)

``````

### Dictionary

#### 创建一个空的Dictionary

``````var namesOfIntegers = [Int : String]() // key类型为Int value类型为String
``````

#### 使用字面量方式创建一个Dictionary

``````var airports: [String: String] = ["YYZ":"Toronto Pearson","DUB":"Dublin"]
``````

#### 当Dictionary内元素类型相同时,由于Swift自动推导的功能,所以不需要给定类型

``````var airports = ["YYZ":"Toronto Pearson","DUB":"Dublin"]
``````

#### count 字典中包含的元素个数

``````print("airports 包含 \(airports.count)个元素")
``````

#### isEmpty 判断字典是不是空的,如果为空则返回true,否则返回false

``````if airports.isEmpty {
print("airports 字典是空的")
}else{
print("airports 字典不是空的")
}
``````

#### updateValue

``````if let oldValue = airports.updateValue("Dublin", forKey: "DUB"){
print("oldValue 是airports 中的值")
}

let airportName = airports["DUB"]
``````

#### 字典的赋值方法

``````airports["APL"] = "Apple International"
``````

#### 字典的两种移除元素的方法

``````airports["APL"] = nil

airports.removeValue(forKey: "DUB")
``````

#### 遍历所有元素,已key:value的方式打印

``````for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
``````

#### 遍历字典中所有的key

``````for airportCode in airports.keys {
print("\(airportCode)")
}
``````

#### 遍历字典中所有的value

``````for airportName in airports.values {
print("\(airportName)")
}
``````

#### 字典中所有的key作为一个数组返回

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

#### 字典中所有的value作为一个数组返回

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