集合类型
集合的可变性
如果你创建一个数组,集合,或字典变量,那么你可以添加,删除,修改集合中的元素。
如果你创建了数组,集合,或字典常量,那么你就不能添加,删除,修改集合中的元素。
数组
元素类型相同的有序的集合
创建空数组
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]
创建一个带默认值的数组
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
- repeating 要重复的值
- count 重复的次数,数组的长度
两个数组连接成一个数组
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"]
// shoppingList has been initialized with two initial items
自动推断类型
var shoppingList = ["Eggs", "Milk"]
调用和修改数组
- 只读属性count获取数组长度
print("The shopping list contains \(shoppingList.count) items.")
// Prints "The shopping list contains 2 items."
- isEmpty属性检查数组是否为空
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]
// firstItem is equal to "Eggs"
- 通过索引修改索引指向的元素
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 item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
Set集合
没有相同值的无序集合
哈希值
set集合的元素必须可以得到哈希值。
创建并初始化一个set集合
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// Prints "letters is of type Set<Character> with 0 items."
清空Set
letters.insert("a")
// letters now contains 1 value of type Character
letters = []
// letters is now an empty set, but is still of type Set<Character>
使用数组创建一个Set
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items
访问和修改Set
- 只读属性count获取Set集合的元素数量
print("I have \(favoriteGenres.count) favorite music genres.")
// Prints "I have 3 favorite music genres.
- isEmpty属性,Set集合count是否0
if favoriteGenres.isEmpty {
print("As far as music goes, I'm not picky.")
} else {
print("I have particular music preferences.")
}
// Prints "I have particular music preferences.
- insert(_:)方法,往Set集合里插入一个元素
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items”
- remove(_:)方法,移除Set集合中指定的元素,如果存在返回改元素,不存在返回nil
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
// Prints "Rock? I'm over it."
- removeAll()方法,移除Set集合中所有的元素
- contains(_:)方法,判断Set集合中是否存在指定的元素
if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
}
// Prints "It's too funky in here."
- sorted()方法,默认从小到大的顺序以数组的形式返回Set集合
let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
遍历Set集合
for genre in favoriteGenres {
print("\(genre)")
}
// Jazz
// Hip hop
// Classical
连接两个Set集合的方法
- a.intersection(b) 创建一个新的Set集合,只包括两个Set集合中相同的元素
- a.symmetricDifference(b) 创建一个新的集合,不包括两个集合中相同的元素
- a.union(b)创建一个新集合,包括所有的元素
- a.subtracting(b)创建一个新的集合,不包括b的任何元素
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.intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
判断一个集合是不是另一个集合的子
- a.isSubset(of:b) a是不是b的子集合
- a.isSuperset(of:b) b是不是a的子集合
- a.isStrictSubset(of:b) a是不是b的子集合,并且b至少有一个元素不是a的元素。
- a.isStrictSuperset(of:b) b是不是a的子集合,并且a至少有一个元素不是b的元素。
- a.isDisjoint(with:b) a和b是否有相同的元素
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true
字典(Dictionaries)
创建一个空字典
var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary
用字典语法创建字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
访问和修改字典
- count属性获取字典内容的数量
print("The airports dictionary contains \(airports.count) items.")
// Prints "The airports dictionary contains 2 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.
- 增加一对新的元素
airports["LHR"] = "London"
// the airports dictionary now contains 3 items
- 修改对应key值的元素
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"
-updateValue(_:forKey:) 增加或修改对应key的值,如果旧值存在返回旧值,否则返回nil。
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."
-removeValue(forKey:) 移除指定key的值,值存在返回对应的值,否则返回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."
遍历字典
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
分别遍历Key和值
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