Swift3.0之集合類型

一廓鞠、數(shù)組
通過初始化語法創(chuàng)建一個特定類型的空數(shù)組

var someInts = [Int]()
print("someInts is of type [Int] with\(someInts.count) items")

如果上文已提供類型信息担租,像函數(shù)參數(shù)或者已有類型的常變量砖顷,可以使用空數(shù)組字面量來創(chuàng)建空數(shù)組创南,寫作[]

someInts.append(3)
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]

創(chuàng)建一個帶默認(rèn)值的數(shù)組
Swift提供初始化器來創(chuàng)建一種所有值為同一個默認(rèn)值的特定大小的數(shù)組涩嚣。通過repeating:來傳遞一個默認(rèn)值崇众,通過count:來傳遞這個值出現(xiàn)的次數(shù)。如下:

var threeDoubles = Array(repeating:0.0,count:3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

兩數(shù)組合并組成新數(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ù)組
如下格式:
[value 1, value2, value3]

var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items

一般你不用寫數(shù)組的類型航厚,因為數(shù)組字面量中的所有值都為同種類型顷歌,Swift可以自動算出正確地類型。

var shoppingList = ["Eggs", "Milk"]

訪問和修改數(shù)組
可以通過其方法和屬性來訪問修改一個數(shù)組幔睬,或者使用下標(biāo)語法
(1) 數(shù)組item的數(shù)目眯漩,使用count屬性

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

(2)使用isEmpty來判斷數(shù)組是否為空
(3)通過append(_:)的方式來添加新的item

shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes

(4)檢索數(shù)組的值,通過下標(biāo)的方式

var firstItem = shoppingList[0]
// firstItem is equal to "Eggs"

注意:swift中數(shù)組下標(biāo)總是以0開頭的
(5)可以通過下標(biāo)語法來直接修改值

shoppingList[0] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs"

(6)可以通過下標(biāo)來改變一個范圍的值

shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items

注意:不能使用下標(biāo)來拼接一個新的item到數(shù)組的最后
(7)在特定的索引下麻顶,插入一個數(shù)組赦抖,使用 insert(_:at:)方法

shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list

(8)使用remove(at:)來移除item,返回被移除的item

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

注意:訪問超出邊界會報錯
(9)移除數(shù)組最后一個item辅肾,最好使用removeLast(),省去查找數(shù)組個數(shù)的屬性队萤,同樣,removeLast返回被移除的item

let apples = shoppingList.removeLast()

(10)遍歷一個數(shù)組

for item in shoppingList {
print(item)
}

(11)如果你需要每一個item的整形指數(shù)以及值矫钓,可以使用enumerated()來遍歷數(shù)組要尔。那么返回的值為指數(shù)和對應(yīng)的值組成的元組。

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

二新娜、集合

存儲一些同一類型沒有順序的值盈电,并且每個item只出現(xiàn)一次。
為了能讓類型儲存在集合當(dāng)中杯活,它必須是可哈希的——就是說類型必須提供計算它自身哈希值的方法。
Swift 的合集類型寫做 Set<Element>熬词,這里的 Element是集合要儲存的類型旁钧。不同與數(shù)組船殉,集合沒有等價的簡寫冒掌。

初始化創(chuàng)建一個空的集合

 var letters = Set<Character>()

如果上文已提供類型信息,通過空的數(shù)組字面量創(chuàng)建一個空的集合

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>

使用數(shù)組字面量初始化一個數(shù)組践美,可以作為一個速成的方式寫進(jìn)更多的值

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

一個set類型不能僅僅通過數(shù)組字面量來推出颜矿,所以set必須能明確的聲明寄猩,但是如果數(shù)組字面量包含的類型與集合初始化的類型一致,集合內(nèi)的類型不用寫出

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

訪問和修改一個集合
(1)count, isEmpty屬性同上
(2)添加item, insert(_:)

favoriteGenres.insert("Jazz")

(3)remove(_:)移除item骑疆,返回被移除的值田篇,如果不包含這個item替废,則返回nil。所有item可以被removeAll()移除

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

(4)檢測是否包含一個item泊柬,使用contains(_:)

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

遍歷合集
for - in . Set 如果按特定的順序椎镣,使用 sorted()方法。

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

集合操作

集合

(1)使用 intersection(:)找出兩個集合共有的部分并成為新的集合
(2)使用symmetricDifference(
:)找出連個集合各自用的值兽赁,不是共有的
(3)union(:)合并兩個集合
(4)subtracting(
:)元素不在指定的集合

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]

從屬和等價關(guān)系
(1)使用= 來判斷兩個集合是否完全包含相同元素
(2)isSubset(0f:)來判斷子集合
(3)isSuperset(of:)判斷父集合
(4)isStrictSubset(of:) 或者 isStrictSuperset(of:)來判斷是否一個集合完全是子集或父集合状答,而不是等同于一個特定的集合
(5)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

三、字典
創(chuàng)建空字典,如果已知道類型刀崖,可寫成[:]

var namesOfIntegers = [Int: String]()
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ù)組一樣惊科,如果和初始化的鍵值類型一致,那么就不用再寫相關(guān)類型亮钦。

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

訪問和修改字典
(1)count和isEmpty屬性馆截。
(2)下標(biāo)腳本給字典添加新元素。使用正確類型的新鍵作為下標(biāo)腳本的索引或悲,然后賦值一個正確類型的值

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

同樣可以通過key修改Value

airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"

(3)使用updateValue(:forkey:)來設(shè)置或更新一個特定key所對應(yīng)的值孙咪。做完更新后,這個方法返回舊的Value巡语。
updateValue(
:forKey:)方法返回一個字典值類型的可選項值翎蹈。比如對于儲存 String值的字典來說,方法會返回 String?類型的值男公,或者說“可選的 String”荤堪。這個可選項包含了鍵的舊值如果更新前存在的話,否則就是 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."

同樣可以使用下標(biāo)腳本語法來從字典的特點鍵中取回值枢赔。由于可能請求的鍵沒有值澄阳,字典的下標(biāo)腳本返回可選的字典值類型。如果字典包含了請求的鍵的值踏拜,下標(biāo)腳本就返回一個包含這個鍵的值的可選項碎赢。否則,下標(biāo)腳本返回 nil :

使用下標(biāo)腳本語法給一個鍵賦值 nil來從字典當(dāng)中移除一個鍵值對:

airports["APL"] = "Apple International"
// "Apple International" is not the real airport for APL, so delete it
airports["APL"] = nil
// APL has now been removed from the dictionary

使用 removeValueForKey(_:)來從字典里移除鍵值對速梗。這個方法移除鍵值對如果他們存在的話肮塞,并且返回移除的值,如果值不存在則返回 nil:

if let removedValue = airports.removeValueForKey("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-in循環(huán)來遍歷字典的鍵值對姻锁。字典中的每一個元素返回為 (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

需要和接收 Array實例的 API 一起使用字典的鍵或值,就用 keys或 values屬性來初始化一個新數(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)容合作請聯(lián)系作者
  • 序言:七十年代末位隶,一起剝皮案震驚了整個濱河市拷窜,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖篮昧,帶你破解...
    沈念sama閱讀 222,729評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赋荆,死亡現(xiàn)場離奇詭異,居然都是意外死亡恋谭,警方通過查閱死者的電腦和手機糠睡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來疚颊,“玉大人狈孔,你說我怎么就攤上這事〔囊澹” “怎么了均抽?”我有些...
    開封第一講書人閱讀 169,461評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長其掂。 經(jīng)常有香客問我油挥,道長,這世上最難降的妖魔是什么款熬? 我笑而不...
    開封第一講書人閱讀 60,135評論 1 300
  • 正文 為了忘掉前任深寥,我火速辦了婚禮,結(jié)果婚禮上贤牛,老公的妹妹穿的比我還像新娘惋鹅。我一直安慰自己,他們只是感情好殉簸,可當(dāng)我...
    茶點故事閱讀 69,130評論 6 398
  • 文/花漫 我一把揭開白布闰集。 她就那樣靜靜地躺著,像睡著了一般般卑。 火紅的嫁衣襯著肌膚如雪武鲁。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,736評論 1 312
  • 那天蝠检,我揣著相機與錄音沐鼠,去河邊找鬼。 笑死叹谁,一個胖子當(dāng)著我的面吹牛迟杂,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播本慕,決...
    沈念sama閱讀 41,179評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼侧漓!你這毒婦竟也來了锅尘?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,124評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎藤违,沒想到半個月后浪腐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,657評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡顿乒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,723評論 3 342
  • 正文 我和宋清朗相戀三年议街,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片璧榄。...
    茶點故事閱讀 40,872評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡特漩,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出骨杂,到底是詐尸還是另有隱情涂身,我是刑警寧澤,帶...
    沈念sama閱讀 36,533評論 5 351
  • 正文 年R本政府宣布搓蚪,位于F島的核電站蛤售,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏妒潭。R本人自食惡果不足惜悴能,卻給世界環(huán)境...
    茶點故事閱讀 42,213評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望雳灾。 院中可真熱鬧漠酿,春花似錦、人聲如沸佑女。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽团驱。三九已至摸吠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間嚎花,已是汗流浹背寸痢。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留紊选,地道東北人啼止。 一個月前我還...
    沈念sama閱讀 49,304評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像兵罢,于是被迫代替她去往敵國和親献烦。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,876評論 2 361

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