swift - 集合

數(shù)組(Swift 的 Array類型被橋接到了基礎(chǔ)框架的 NSArray類上。)

數(shù)組創(chuàng)建

// Swift 數(shù)組的類型完整寫法是 Array<Element>
// 同樣可以簡(jiǎn)寫數(shù)組的類型為 [Element]。
// 更推薦簡(jiǎn)寫并且全書涉及到數(shù)組類型的時(shí)候都會(huì)使用簡(jiǎn)寫。
// 創(chuàng)建一個(gè)空數(shù)組
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) 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]

//使用默認(rèn)值創(chuàng)建數(shù)組
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

//通過連接兩個(gè)數(shù)組來創(chuàng)建數(shù)組
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]

//使用數(shù)組字面量創(chuàng)建數(shù)組
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
//依托于 Swift 的類型推斷,如果你用包含相同類型值的數(shù)組字面量初始化數(shù)組贩猎,就不需要寫明數(shù)組的類型。 shoppingList的初始化可以寫得更短
var shoppingList = ["Eggs", "Milk"]
// 避免推斷
var shoppingList = ["Eggs", "Milk"] as [Any]

數(shù)組操作

//.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."

//添加元素
shoppingList.append("Flour")
shoppingList[0] = "Six eggs"
shoppingList[4...6] = ["Bananas", "Apples"]

//插入
shoppingList.insert("Maple Syrup", at: 0)

//刪除
let mapleSyrup = shoppingList.remove(at: 0)

//另外,可以使用加賦值運(yùn)算符 ( +=)來在數(shù)組末尾添加一個(gè)或者多個(gè)同類型元素:
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items

//取值
var firstItem = shoppingList[0]

數(shù)組遍歷

//你可以用 for-in循環(huán)來遍歷整個(gè)數(shù)組中值的合集:
for item in shoppingList {
    print(item)
}
//你需要每個(gè)元素以及值的整數(shù)索引坞嘀,使用 enumerated()方法來遍歷數(shù)組。 enumerated()方法返回?cái)?shù)組中每一個(gè)元素的元組霎苗,包含了這個(gè)元素的索引和值姆吭。你可以分解元組為臨時(shí)的常量或者變量作為遍歷的一部分:
for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}

合集(Swift 的 Set類型橋接到了基礎(chǔ)框架的 NSSet類上。)

合集創(chuàng)建(合集類型不能從數(shù)組字面量推斷出來唁盏,所以 Set類型必須被顯式地聲明)

//你可以使用初始化器語法來創(chuàng)建一個(gè)確定類型的空合集:
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
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>

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items


合集操作

//合集當(dāng)中元素的數(shù)量内狸,檢查它的只讀 count
print("I have \(favoriteGenres.count) 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.")
}
// prints "I have particular music preferences."

//插入
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items

//刪除
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."

//包含
if favoriteGenres.contains("Funk") {
    print("I get up on the good foot.")
} else {
    print("It's too funky in here.")
}

合集遍歷

//你可以在 for-in循環(huán)里遍歷合集的值。
for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop

//Set類型是無序的厘擂。要以特定的順序遍歷合集的值昆淡,使用 sorted()方法
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}

合集操作

/**
使用 A.intersection(B:)  : A∩B 
使用 A.symmetricDifference(B:):A∪B -  A∩B 
使用 A.union(B:) : A∪B
使用 A.subtracting(B:)   : A-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]

字典(Dictionary橋接到了基礎(chǔ)框架的 NSDictionary類。)

字典創(chuàng)建

//Swift 的字典類型寫全了是這樣的: Dictionary<Key, Value>刽严,
//其中的 Key是用來作為字典鍵的值類型昂灵, Value就是字典為這些鍵儲(chǔ)存的值的類型。
//簡(jiǎn)寫的形式來寫字典的類型為 [Key: Value]。盡管兩種寫法是完全相同的眨补,但本書所有提及字典的地方都會(huì)使用簡(jiǎn)寫形式管削。
var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

//用字典字面量創(chuàng)建字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
//與數(shù)組一樣,如果你用一致類型的字典字面量初始化字典撑螺,就不需要寫出字典的類型了含思。 airports的初始化就能寫的更短:
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
//避免類型推斷
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin",2:"zzzz"] as [AnyHashable : String]

字典操作

//使用 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.")
}

// 賦值
airports["LHR"] = "London"
//更改
airports["LHR"] = "London Heathrow"

//updateValue(_:forKey:)方法來設(shè)置或者更新特點(diǎn)鍵的值
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}

//刪除
airports["APL"] = nil
//airports.removeValue 刪除
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.")
}

字典遍歷

//for-in循環(huán)來遍歷字典的鍵值對(duì)
for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
//你同樣可以通過訪問字典的 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

//需要和接收 Array實(shí)例的 API 一起使用字典的鍵或值,就用 keys或 values屬性來初始化一個(gè)新數(shù)組
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末甘晤,一起剝皮案震驚了整個(gè)濱河市含潘,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌线婚,老刑警劉巖遏弱,帶你破解...
    沈念sama閱讀 222,000評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異塞弊,居然都是意外死亡漱逸,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門居砖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來虹脯,“玉大人,你說我怎么就攤上這事奏候⊙” “怎么了?”我有些...
    開封第一講書人閱讀 168,561評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵蔗草,是天一觀的道長(zhǎng)咒彤。 經(jīng)常有香客問我,道長(zhǎng)咒精,這世上最難降的妖魔是什么镶柱? 我笑而不...
    開封第一講書人閱讀 59,782評(píng)論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮模叙,結(jié)果婚禮上歇拆,老公的妹妹穿的比我還像新娘。我一直安慰自己范咨,他們只是感情好故觅,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,798評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著渠啊,像睡著了一般输吏。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上替蛉,一...
    開封第一講書人閱讀 52,394評(píng)論 1 310
  • 那天贯溅,我揣著相機(jī)與錄音拄氯,去河邊找鬼笋熬。 笑死疟呐,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的奈搜。 我是一名探鬼主播罚缕,決...
    沈念sama閱讀 40,952評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼艇纺,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了邮弹?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,852評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤蚓聘,失蹤者是張志新(化名)和其女友劉穎腌乡,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體夜牡,經(jīng)...
    沈念sama閱讀 46,409評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡与纽,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,483評(píng)論 3 341
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了塘装。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片急迂。...
    茶點(diǎn)故事閱讀 40,615評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖蹦肴,靈堂內(nèi)的尸體忽然破棺而出僚碎,到底是詐尸還是另有隱情,我是刑警寧澤阴幌,帶...
    沈念sama閱讀 36,303評(píng)論 5 350
  • 正文 年R本政府宣布勺阐,位于F島的核電站,受9級(jí)特大地震影響矛双,放射性物質(zhì)發(fā)生泄漏渊抽。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,979評(píng)論 3 334
  • 文/蒙蒙 一议忽、第九天 我趴在偏房一處隱蔽的房頂上張望懒闷。 院中可真熱鬧,春花似錦栈幸、人聲如沸愤估。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽灵疮。三九已至,卻和暖如春壳繁,著一層夾襖步出監(jiān)牢的瞬間震捣,已是汗流浹背荔棉。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蒿赢,地道東北人润樱。 一個(gè)月前我還...
    沈念sama閱讀 49,041評(píng)論 3 377
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像羡棵,于是被迫代替她去往敵國和親壹若。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,630評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容