Swift 提供了三種主要的集合類型:數(shù)組Array
所刀、合集Set
還有字典Dictionary
衙荐。數(shù)組是有序的值的集合,合集是唯一值的無序集合浮创,字典是無序的鍵值對集合忧吟。賦值給變量的集合就是可變的。賦值給常量的集合是不可變的蒸矛。
1. 數(shù)組
數(shù)組類型的完整寫法為Array<Element>
瀑罗,Element是數(shù)組允許存入的值的類型,如Array<Int>
,但常常用[Int]
來代替此寫法雏掠。
創(chuàng)建一個數(shù)組
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// 結果為: "someInts is of type [Int] with 0 items."
創(chuàng)建好的數(shù)組可以添加元素或者被清空:
someInts.append(3)
// someInts 現(xiàn)在包含一個Int類型的元素
someInts = []
// someInts 現(xiàn)在被清空斩祭,但依然是[Int]類型
使用默認值創(chuàng)建數(shù)組
使用Array(repeating: count:)
方法,自定義一定數(shù)量的默認值組成的數(shù)組:
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles 是[Double]類型, 值為[0.0, 0.0, 0.0]
通過連接兩個數(shù)組來創(chuàng)建數(shù)組
兩個兼容類型的數(shù)組用加運算符(+
)可創(chuàng)建一個新數(shù)組:
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles 是[Double]類型, 值為 [2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles 被推斷為[Double]類型, 值為 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
使用數(shù)組字面量創(chuàng)建數(shù)組
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList 被初始化為含有兩個字符串元素的數(shù)組
或者:
var shoppingList = ["Eggs", "Milk"]
// 雖然未寫shoppingList類型乡话,但由于所有元素都是String類型摧玫,所以數(shù)組被推斷為[String]類型
訪問和修改數(shù)組
要得出數(shù)組中元素的數(shù)量,使用count
屬性:
print("The shopping list contains \(shoppingList.count) items.")
// 結果為: "The shopping list contains 2 items."
使用isEmpty
屬性來檢查count屬性是否為0:
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
// 結果為: "The shopping list is not empty."
使用append(_:)
方法給數(shù)組末尾添加新的元素:
shoppingList.append("Flour")
// shoppingList 現(xiàn)在包含3個元素
或者使用"+=
"運算符來代替上面的方法:
shoppingList += ["Baking Powder"]
// shoppingList 現(xiàn)在包含4個元素
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList 現(xiàn)在包含7個元素
通過下標腳本語法來從數(shù)組當中取回一個值绑青,在數(shù)組名后的方括號內傳入你想要取回的值的索引:
var firstItem = shoppingList[0]
// firstItem 的值為 "Eggs"
// 注意: 數(shù)組的下標從0開始
使用下標腳本語法來改變給定索引中已經存在的值:
shoppingList[0] = "Six eggs"
// shoppingList數(shù)組第一個元素被更改為"Six eggs"
或者更改一個范圍的值:
shoppingList[4...6] = ["Bananas", "Apples"]
// 將4诬像、5、6三個元素替換為"Bananas", "Apples"兩個元素
// shoppingList 現(xiàn)在包含6個元素
要把元素插入到特定的索引位置闸婴,調用數(shù)組的insert(_:at:)
方法:
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList 現(xiàn)在包含7個元素
// "Maple Syrup" 成為數(shù)組的第一個元素
使用remove(at:)
方法來移除一個元素坏挠,并且返回這個元素值:
let mapleSyrup = shoppingList.remove(at: 0)
// 位置0的元素被移除
// shoppingList 現(xiàn)在包含6個元素, 不再擁有"Maple Syrup"
// mapleSyrup常量的值為 "Maple Syrup"
如果你想要移除數(shù)組最后一個元素,使用removeLast()
方法而不是removeAtIndex(_:):
let apples = shoppingList.removeLast()
// 數(shù)組最后一個元素被移除
// shoppingList 現(xiàn)在包含5個元素邪乍,不再擁有 apples
// apples 常量的值為 "Apples"
遍歷一個數(shù)組
使用for...in
來遍歷整個數(shù)組:
for item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
如果需要遍歷每個元素的索引和值降狠,使用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
2. 合集
合集:同一類型,值不重復庇楞,無序地儲存的集合
Set類型的哈希值
哈希值是Int
值榜配,若a == b,意味著 a.hashValue == b.hashValue吕晌。
創(chuàng)建并初始化一個空合集
var letters = Set<Character>()
// 和數(shù)組不一樣蛋褥,此處沒有簡寫
print("letters is of type Set<Character> with \(letters.count) items.")
// 結果為: "letters is of type Set<Character> with 0 items."
創(chuàng)建好的合集可以添加元素或者被清空:
letters.insert("a")
// letters 現(xiàn)在包含一個字符元素
letters = []
// letters 現(xiàn)在為空,但依然是Set<Character>類型
使用數(shù)組字面量創(chuàng)建合集
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items
或者簡寫為:
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
// favoriteGenres被推斷為Set<String>類型
訪問和修改合集
要得出合集中元素的數(shù)量睛驳,使用count
屬性:
print("I have \(favoriteGenres.count) favorite music genres.")
// 結果為: "I have 3 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.")
}
// 結果為: "I have particular music preferences."
使用insert(_:)
方法來添加一個新的元素到合集:
favoriteGenres.insert("Jazz")
// favoriteGenres 現(xiàn)在包含4個元素
調用合集的remove(_:)
方法移除一個元素烙心,如果元素是合集的元素就移除它并返回被移除的值膜廊,如果合集沒有這個元素就返回 nil。另外:合集當中所有的元素可以用removeAll()
一次移除:
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
// 結果為: "Rock? I'm over it."
檢查合集是否包含特定元素弃理,使用contains(_:)
方法:
if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
}
// 結果為: "It's too funky in here."
遍歷合集
使用for...in
語句遍歷:
for genre in favoriteGenres {
print("\(genre)")
}
// Classical
// Jazz
// Hip hop
Set類型是無序的溃论,使用sorted()
方法將其變?yōu)橛行驍?shù)組:
for genre in favoriteGenres.sorted() {
print("\(genre)")
}
// Classical
// Hip hop
// Jazz
合集與合集之間的操作
- 使用
intersection(_:)
方法來創(chuàng)建一個只包含兩個合集共有值的新合集 - 使用 symmetricDifference(_:)方法來創(chuàng)建一個只包含兩個合集各自有的非共有值的新合集
- 使用
union(_:)
方法來創(chuàng)建一個包含兩個合集所有值的新合集 - 使用
subtracting(_:)
方法來創(chuàng)建一個兩個合集當中不包含某個合集值的新合集。舉個栗子:
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]
合集成員關系和相等性
- 使用“相等”運算符 (
==
)來判斷兩個合集是否包含有相同的值 - 使用
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. 字典
字典類型的完整寫法為Dictionary<Key, Value>
,通常簡寫為[Key: Value]
辆苔,如[Int, String]
算灸。
創(chuàng)建一個空字典
var namesOfIntegers = [Int: String]()
// namesOfIntegers 是一個空的[Int: String]類型的字典
修改字典:
namesOfIntegers[16] = "sixteen"
// namesOfIntegers 現(xiàn)在包含一個鍵值對
namesOfIntegers = [:]
// namesOfIntegers 被置空,但仍然是[Int: String]類型
用字典字面量創(chuàng)建字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
或者簡寫為:
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
// airports 被推斷為 [String: String]類型
訪問和修改字典
使用count
只讀屬性找出字典鍵值對數(shù)量:
print("The airports dictionary contains \(airports.count) items.")
// 結果為: "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.")
}
// 結果為: "The airports dictionary is not empty."
用下標腳本給字典添加或修改元素:
airports["LHR"] = "London"
// airports現(xiàn)在包含三個鍵值對
airports["LHR"] = "London Heathrow"
// 字典中"LHR"對應的值更改為"London Heathrow"
使用updateValue(_:forKey:)
方法修改字典后驻啤,返回修改前的值菲驴,如果沒有修改前的值則返回nil
:
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
// 結果為: "The old value for DUB was Dublin."
如果字典包含了請求的鍵,下標腳本就返回對應的值骑冗。否則赊瞬,下標腳本返回 nil
:
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 International"
airports["APL"] = nil
// APL 這個鍵被刪除
另外,使用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."
遍歷字典
使用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
獲取鍵或值的集合:
let airportCodes = [String](airports.keys)
// airportCodes 的值為 ["YYZ", "LHR"]
let airportNames = [String](airports.values)
// airportName 的值為 ["Toronto Pearson", "London Heathrow"]