Swift 3.0之四、集合類型

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

同樣谤绳,通過keysvalues屬性訪問鍵或值的集合:

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"]
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市袒哥,隨后出現(xiàn)的幾起案子缩筛,更是在濱河造成了極大的恐慌,老刑警劉巖堡称,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瞎抛,死亡現(xiàn)場離奇詭異,居然都是意外死亡却紧,警方通過查閱死者的電腦和手機婿失,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來啄寡,“玉大人,你說我怎么就攤上這事哩照⊥ξ铮” “怎么了?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵飘弧,是天一觀的道長识藤。 經常有香客問我砚著,道長,這世上最難降的妖魔是什么痴昧? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任稽穆,我火速辦了婚禮,結果婚禮上赶撰,老公的妹妹穿的比我還像新娘舌镶。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著仆潮,像睡著了一般跳芳。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上窃蹋,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天,我揣著相機與錄音,去河邊找鬼墨技。 笑死,一個胖子當著我的面吹牛挎狸,可吹牛的內容都是我干的扣汪。 我是一名探鬼主播,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼伟叛,長吁一口氣:“原來是場噩夢啊……” “哼私痹!你這毒婦竟也來了?” 一聲冷哼從身側響起统刮,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤紊遵,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后侥蒙,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體暗膜,經...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年鞭衩,在試婚紗的時候發(fā)現(xiàn)自己被綠了学搜。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡论衍,死狀恐怖瑞佩,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情坯台,我是刑警寧澤炬丸,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站蜒蕾,受9級特大地震影響稠炬,放射性物質發(fā)生泄漏焕阿。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一首启、第九天 我趴在偏房一處隱蔽的房頂上張望暮屡。 院中可真熱鬧,春花似錦毅桃、人聲如沸褒纲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽外厂。三九已至,卻和暖如春代承,著一層夾襖步出監(jiān)牢的瞬間汁蝶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工论悴, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留掖棉,地道東北人。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓膀估,卻偏偏與公主長得像幔亥,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子察纯,可洞房花燭夜當晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內容