
Swift 語言提供Arrays、Sets和Dictionaries三種基本的集合類型用來存儲(chǔ)集合數(shù)據(jù)。數(shù)組(
Arrays)是有序數(shù)據(jù)的集。集合(Sets)是無序無重復(fù)數(shù)據(jù)的集。字典(Dictionaries)是無序的鍵值對(duì)的集。
1 .數(shù)組 Arrays
數(shù)組使用有序列表存儲(chǔ)同一類型的多個(gè)值。相同的值可以多次出現(xiàn)在一個(gè)數(shù)組的不同位置中。這和OC中的類似。
- 1.1 數(shù)組的簡(jiǎn)單語法
建立Swift 數(shù)組應(yīng)該遵循像
Array<Element>這樣的形式,其中Element是這個(gè)數(shù)組中唯一允許存在的數(shù)據(jù)類型。我們也可以使用像[Element]這樣的簡(jiǎn)單語法。盡管兩種形式在功能上是一樣的,但是推薦較短的那種,而且在本文中都會(huì)使用這種形式來使用數(shù)組。
- 1.2 創(chuàng)建一個(gè)空數(shù)組、
我們可以使用構(gòu)造語法來創(chuàng)建一個(gè)由特定數(shù)據(jù)類型構(gòu)成的空數(shù)組,就像上面說的,
[Element]這樣的簡(jiǎn)單語法
var someInts = [Int]()
print("someInts is of type [Int] with \\(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."

如上圖,通過構(gòu)造函數(shù)的類型,
someInts的值類型被推斷為[Int]。.
當(dāng)然你不指定數(shù)據(jù)類型也是可以建立的,為
[Any]類型,
如果代碼上下文中已經(jīng)提供了類型信息,例如一個(gè)函數(shù)參數(shù)或者一個(gè)已經(jīng)定義好類型的常量或者變量,我們可以使用空數(shù)組語句創(chuàng)建一個(gè)空數(shù)組,它的寫法很簡(jiǎn)單:
[]:
someInts.append(3)
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]
注意:這種方式someInts = []新建的數(shù)組保持原來的類型。
- 1.3 .創(chuàng)建一個(gè)帶有默認(rèn)值的數(shù)組
Swift 中的Array類型還提供一個(gè)可以創(chuàng)建特定大小并且所有數(shù)據(jù)都被默認(rèn)的構(gòu)造方法。我們可以把準(zhǔn)備加入新數(shù)組的適當(dāng)類型的初始值(
repeatedValue)和數(shù)組數(shù)據(jù)項(xiàng)的數(shù)量(count)傳入數(shù)組的構(gòu)造函數(shù)
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
- 1.4 通過兩個(gè)數(shù)組相加創(chuàng)建一個(gè)數(shù)組
我們可以使用加法操作符(+)來組合兩種已存在的相同類型數(shù)組。新數(shù)組的數(shù)據(jù)類型會(huì)被從兩個(gè)數(shù)組的數(shù)據(jù)類型中推斷出來
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
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]
- 1.5 用數(shù)組文本直接構(gòu)造數(shù)組
我們可以使用數(shù)組文本來進(jìn)行數(shù)組構(gòu)造,這是一種用一個(gè)或者多個(gè)數(shù)值構(gòu)造數(shù)組的簡(jiǎn)單方法。數(shù)組文本是一系列由逗號(hào)分割并由方括號(hào)包含的數(shù)值:
[value 1, value 2, value 3]。
下面的示例創(chuàng)建一個(gè)名為shoppingList的數(shù)組存儲(chǔ)String值:
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
shoppingList變量被聲明為“字符串值類型的數(shù)組“,記作[String]。 因?yàn)檫@個(gè)數(shù)組被規(guī)定只有String一種數(shù)據(jù)結(jié)構(gòu),所以只有String類型可以在其中被存取。 在這里,shoppinglist數(shù)組由兩個(gè)String值("Eggs" 和"Milk")構(gòu)造,并且由字面量定義。
由于 Swift 的類型推斷機(jī)制,當(dāng)我們用字面量構(gòu)造只擁有相同類型值數(shù)組的時(shí)候,我們不必把數(shù)組的類型定義清楚。shoppinglist的構(gòu)造也可以這樣寫:var shoppingList = ["Eggs", "Milk"]
因?yàn)樗凶置媪恐械闹刀际窍嗤念愋?,Swift 可以推斷出[String]是shoppinglist中變量的正確類型。
- 1.6 訪問和修改數(shù)組
我們可以通過數(shù)組的方法和屬性來訪問和修改數(shù)組,或者使用下標(biāo)語法。
(1):可以使用數(shù)組的只讀屬性count來獲取數(shù)組中的數(shù)據(jù)項(xiàng)數(shù)量:
var shoppingList: [String] = ["Eggs", "Milk"]
print("The shoppingList contains \\(shoppingList.count) items.")
// Prints "The shoppingList contains 2 items.
(2):使用布爾值屬性isEmpty作為檢查count屬性的值是否為0
var shoppingList: [String] = ["Eggs", "Milk"]
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
// Prints "The shopping list is not empty."
(3):也可以使用append(_:)方法在數(shù)組后面添加新的數(shù)據(jù)項(xiàng):
var shoppingList: [String] = ["Eggs", "Milk"]
shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes
(4):使用加法賦值運(yùn)算符(+=)也可以直接在數(shù)組后面添加一個(gè)或多個(gè)擁有相同類型的數(shù)據(jù)項(xiàng):
var shoppingList: [String] = ["Eggs", "Milk"]
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
(5):可以直接使用下標(biāo)語法來獲取數(shù)組中的數(shù)據(jù)項(xiàng),把我們需要的數(shù)據(jù)項(xiàng)的索引值直接放在數(shù)組名稱的方括號(hào)中,和OC一樣索引從0開始:
var firstItem = shoppingList[0]
// firstItem is equal to "Eggs"
(6):我們也可以用下標(biāo)來改變某個(gè)已有索引值對(duì)應(yīng)的數(shù)據(jù)值:
var shoppingList: [String] = ["Eggs", "Milk"]
shoppingList[0] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs"
(7):還可以利用下標(biāo)來一次改變一系列數(shù)據(jù)值,即使新數(shù)據(jù)和原有數(shù)據(jù)的數(shù)量是不一樣的。下面的例子把"Chocolate Spread","Cheese",和"Butter"替換為"Bananas"和 "Apples":
var shoppingList: [String] = ["Eggs", "Milk"]
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
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items
(8):調(diào)用數(shù)組的insert(_:atIndex:)方法來在某個(gè)具體索引值之前添加數(shù)據(jù)項(xiàng):
var shoppingList: [String] = ["Eggs", "Milk"]
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
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list
這次insert(_:atIndex:)方法調(diào)用把值為"Maple Syrup"的新數(shù)據(jù)項(xiàng)插入列表的最開始位置,并且使用0作為索引值
(9):我們可以使用removeAtIndex(_:)方法來移除數(shù)組中的某一項(xiàng)
這個(gè)方法把數(shù)組在特定索引值中存儲(chǔ)的數(shù)據(jù)項(xiàng)移除并且返回這個(gè)被移除的數(shù)據(jù)項(xiàng)(我們不需要的時(shí)候就可以無視它):
var shoppingList: [String] = ["Eggs", "Milk"]
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
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list
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
當(dāng)我們刪除數(shù)組最后一項(xiàng)時(shí)shoppingList.remove(at: shoppingList.count-1),但可以更便捷的使用 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
(10):數(shù)組的遍歷
我們可以使用for-in循環(huán)來遍歷所有數(shù)組中的數(shù)據(jù)項(xiàng):
for item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
如果我們同時(shí)需要每個(gè)數(shù)據(jù)項(xiàng)的值和索引值,可以使用enumerate()方法來進(jìn)行數(shù)組遍歷。enumerate()返回一個(gè)由每一個(gè)數(shù)據(jù)項(xiàng)索引值和數(shù)據(jù)值組成的元組。我們可以把這個(gè)元組分解成臨時(shí)常量或者變量來進(jìn)行遍歷:
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 .集合Sets
集合(Set)用來存儲(chǔ)相同類型并且沒有確定順序的值。當(dāng)集合元素順序不重要時(shí)或者希望確保每個(gè)元素只出現(xiàn)一次時(shí)可以使用集合而不是數(shù)組。
- 2.1 集合類型的哈希值
一個(gè)類型為了存儲(chǔ)在集合中,該類型必須是可哈希化的--也就是說,該類型必須提供一個(gè)方法來計(jì)算它的哈希值。一個(gè)哈希值是
Int類型的,相等的對(duì)象哈希值必須相同,比如a==b,因此必須a.hashValue == b.hashValue。
Swift 的所有基本類型(比如String,Int,Double和Bool)默認(rèn)都是可哈?;模梢宰鳛榧系闹档念愋突蛘咦值涞逆I的類型。沒有關(guān)聯(lián)值的枚舉成員值默認(rèn)也是可哈?;?。
- 2.2 集合類型語法
Swift 中的Set類型被寫為Set<Element>,這里的Element表示Set中允許存儲(chǔ)的類型,和數(shù)組不同的是,集合沒有等價(jià)的簡(jiǎn)化形式。
- 2.3 創(chuàng)建和構(gòu)造一個(gè)空的集合
你可以通過構(gòu)造器語法創(chuàng)建一個(gè)特定類型的空集合:
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."
通過構(gòu)造器,這里的letters變量的類型被推斷為Set<Character>。
.
此外,如果上下文提供了類型信息,比如作為函數(shù)的參數(shù)或者已知類型的變量或常量,像數(shù)組一樣,我們可以通過一個(gè)空的數(shù)組字面量創(chuàng)建一個(gè)空的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>
- 2.4 用數(shù)組數(shù)值創(chuàng)建集合
你可以使用數(shù)組數(shù)值來構(gòu)造集合,并且可以使用簡(jiǎn)化形式寫一個(gè)或者多個(gè)值作為集合元素。
下面的例子創(chuàng)建一個(gè)稱之為favoriteGenres的集合來存儲(chǔ)String類型的值:
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items
一個(gè)Set類型不能從數(shù)組字面量中被單獨(dú)推斷出來,因此Set類型必須顯式聲明。然而,由于 Swift 的類型推斷功能,如果你想使用一個(gè)數(shù)組字面量構(gòu)造一個(gè)Set并且該數(shù)組字面量中的所有元素類型相同,那么你無須寫出Set的具體類型。favoriteGenres的構(gòu)造形式可以采用簡(jiǎn)化的方式代替:var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
由于數(shù)組字面量中的所有元素類型相同,Swift 可以推斷出Set<String>作為favoriteGenres變量的正確類型。
- 2.5 訪問和修改一個(gè)集合
你可以通過Set的屬性和方法來訪問和修改一個(gè)Set?;竞蛿?shù)組一樣,只是Set是無序的沒有索引。
(1)和數(shù)組一樣,為了找出一個(gè)Set中元素的數(shù)量,可以使用其只讀屬性count:
print("I have \\(favoriteGenres.count) favorite music genres.")
// Prints "I have 3 favorite music genres."
(2)和數(shù)組一樣,使用布爾屬性isEmpty作為一個(gè)縮寫形式去檢查count屬性是否為0:
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
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."
(3)和數(shù)組一樣,可以通過調(diào)用Set的insert(_:)方法來添加一個(gè)新元素:
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items
(4)和數(shù)組一樣,Set通過調(diào)用remove(_:)方法去刪除一個(gè)元素,如果該值是該Set的一個(gè)元素則刪除該元素并且返回被刪除的元素值,否則如果該Set不包含該值,則返回nil。另外,Set中的所有元素可以通過它的removeAll()方法刪除。
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
favoriteGenres.insert("Jazz")
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."
(5) 使用contains(_:)方法去檢查Set中是否包含一個(gè)特定的值,數(shù)組也一樣可以使用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."
(6)for-in遍歷一個(gè)集合
你同樣可以用
for-in循環(huán)遍歷一個(gè)Set中的所有值
for genre in favoriteGenres {
print("\\(genre)")
}
// Jazz
// Hip hop
// Classical
(7) sort()方法遍歷
Swift 的Set類型沒有確定的順序,為了按照特定順序來遍歷一個(gè)Set中的值可以使用
sort()方法,它將返回一個(gè)有序數(shù)組,這個(gè)數(shù)組的元素排列順序由操作符'<'對(duì)元素進(jìn)行比較的結(jié)果來確定.
for genre in favoriteGenres.sorted() {
print("\\(genre)")
}
// Classical
// Hip hop
// Jazz
- 2.6 集合操作
你可以高效地完成
Set的一些基本操作,比如把兩個(gè)集合組合到一起,判斷兩個(gè)集合共有元素,或者判斷兩個(gè)集合是否全包含,部分包含或者不相交。就是大學(xué)你學(xué)的集合的概念
(1) 基本集合操作
下面的插圖描述了兩個(gè)集合 a 和 b 以及通過陰影部分的區(qū)域顯示集合各種操作的結(jié)果。
setVennDiagram_2x.png
使用intersect(_:)方法根據(jù)兩個(gè)集合中都包含的值創(chuàng)建的一個(gè)新的集合。(a ∩ b)
使用exclusiveOr(_:)方法根據(jù)在一個(gè)集合中但不在兩個(gè)集合中的值創(chuàng)建一個(gè)新的集合。
使用union(_:)方法根據(jù)兩個(gè)集合的值創(chuàng)建一個(gè)新的集合。(a ∪ b)
使用subtract(_:)方法根據(jù)不在該集合中的值創(chuàng)建一個(gè)新的集合。
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]
(2) 集合成員關(guān)系和相等
下面的插圖描述了三個(gè)集合
a,b和c,以及通過重疊區(qū)域表述集合間共享的元素。集合a是集合b的父集合,因?yàn)?code>a包含了b中所有的元素,相反的,集合b是集合a的子集合,因?yàn)閷儆?code>b的元素也被a包含。集合b和集合c彼此不關(guān)聯(lián),因?yàn)樗鼈冎g沒有共同的元素。
setEulerDiagram_2x.png
使用“等于”運(yùn)算符(==),以確定兩套是否包含所有相同的價(jià)值觀。
使用isSubset(of:)方法,以確定是否所有的一組的值被包含在指定集合。
使用isSuperset(of:)方法確定集是否包含在一組指定的所有值。
使用isStrictSubset(of:)或isStrictSuperset(of:)方法,以確定一組是否是一個(gè)子集或超集,但不等于,指定的一組。
使用isDisjoint(with:)的方法來確定兩個(gè)集合是否有任何共同的值。
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
字典是一種存儲(chǔ)多個(gè)相同類型的值的容器。每個(gè)值(value)都關(guān)聯(lián)唯一的鍵(key),鍵作為字典中的這個(gè)值數(shù)據(jù)的標(biāo)識(shí)符。和數(shù)組中的數(shù)據(jù)項(xiàng)不同,字典中的數(shù)據(jù)項(xiàng)并沒有具體順序。我們?cè)谛枰ㄟ^標(biāo)識(shí)符(鍵)訪問數(shù)據(jù)的時(shí)候使用字典,這種方法很大程度上和我們?cè)诂F(xiàn)實(shí)世界中使用字典查字義的方法一樣。
- 3.1 字典類型快捷語法
Swift 的字典使用Dictionary<Key, Value>定義,其中Key是字典中鍵的數(shù)據(jù)類型,Value是字典中對(duì)應(yīng)于這些鍵所存儲(chǔ)值的數(shù)據(jù)類型。一個(gè)字典的Key類型必須遵循Hashable協(xié)議,就像Set的值類型,是不可以重復(fù)的
- 3.2 創(chuàng)建一個(gè)空字典
像數(shù)組一樣使用構(gòu)造語法創(chuàng)建一個(gè)擁有確定類型的空字典:
var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary
這個(gè)例子創(chuàng)建了一個(gè)[Int: String]類型的空字典來儲(chǔ)存整數(shù)的英語命名。它的鍵是Int型,值是String型。
.
如果上下文已經(jīng)提供了類型信息,我們可以使用空字典數(shù)值來創(chuàng)建一個(gè)空字典,記作[:]
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]
- 3.3 用字典數(shù)值創(chuàng)建字典
我們可以使用字典數(shù)值來構(gòu)造字典,這和我們剛才介紹過的數(shù)組數(shù)值擁有相似語法。字典數(shù)值是一種將一個(gè)或多個(gè)鍵值對(duì)寫作Dictionary集合的快捷途徑。
一個(gè)鍵值對(duì)是一個(gè)key和一個(gè)value的結(jié)合體。在字典數(shù)值中,每一個(gè)鍵值對(duì)的鍵和值都由冒號(hào)分割。這些鍵值對(duì)構(gòu)成一個(gè)列表,其中這些鍵值對(duì)由方括號(hào)包含、由逗號(hào)分割:
[key 1: value 1, key 2: value 2, key 3: value 3]
下面的例子創(chuàng)建了一個(gè)存儲(chǔ)國際機(jī)場(chǎng)名稱的字典。在這個(gè)字典中鍵是三個(gè)字母的國際航空運(yùn)輸相關(guān)代碼,值是機(jī)場(chǎng)名稱:
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
airports字典被聲明為一種[String: String]類型,這意味著這個(gè)字典的鍵和值都是String類型。
.
和數(shù)組一樣,我們?cè)谟米值渥置媪繕?gòu)造字典時(shí),如果它的鍵和值都有各自一致的類型,那么就不必寫出字典的類型。 airports字典也可以用這種簡(jiǎn)短方式定義
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
- 3.4 訪問和修改字典
我們可以通過字典的方法和屬性來訪問和修改字典,或者通過使用下標(biāo)語法
(1) 和數(shù)組一樣,我們可以通過字典的只讀屬性count來獲取某個(gè)字典的數(shù)據(jù)項(xiàng)數(shù)量:
print("The airports dictionary contains \\(airports.count) items.")
// Prints "The airports dictionary contains 2 items."
(2)使用布爾屬性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."
(3) 我們也可以在字典中使用下標(biāo)語法來添加新的數(shù)據(jù)項(xiàng)??梢允褂靡粋€(gè)恰當(dāng)類型的鍵作為下標(biāo)索引,并且分配恰當(dāng)類型的新值,像OC一樣
airports["LHR"] = "London"
// the airports dictionary now contains 3 items
(4) 同樣可以使用上面的方法修改值
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"
(5) 字典的updateValue(_:forKey:)更新值
字典的
updateValue(_:forKey:)方法可以設(shè)置或者更新特定鍵對(duì)應(yīng)的值。就像上面所示的下標(biāo)示例,updateValue(_:forKey:)方法在這個(gè)鍵不存在對(duì)應(yīng)值的時(shí)候會(huì)設(shè)置新值或者在存在時(shí)更新已存在的值。和上面的下標(biāo)方法不同的,updateValue(_:forKey:)這個(gè)方法返回更新值之前的原值。這樣使得我們可以檢查更新是否成功。
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB")
{
print("The old value for DUB was \\(oldValue).")
}
else
{
print("The old value was nil")
}
// Prints "The old value for DUB was Dublin."
當(dāng)更新的鍵不存在時(shí),返回nil
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DU")
{
print("The old value for DU was \\(oldValue).")
}
else
{
print("The old value was nil")
}
// Prints "The old value was nil"
(6) 我們也可以使用下標(biāo)語法來在字典中檢索特定鍵對(duì)應(yīng)的值。因?yàn)橛锌赡苷?qǐng)求的鍵沒有對(duì)應(yīng)的值存在,字典的下標(biāo)訪問會(huì)返回對(duì)應(yīng)值的類型的可選值。如果這個(gè)字典包含請(qǐng)求鍵所對(duì)應(yīng)的值,下標(biāo)會(huì)返回一個(gè)包含這個(gè)存在值的可選值,否則將返回nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \\(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// Prints "The name of the airport is Dublin Airport."
(6) 用nil 移除一個(gè)鍵值對(duì)
我們還可以使用下標(biāo)語法來通過給某個(gè)鍵的對(duì)應(yīng)值賦值為nil來從字典里移除一個(gè)鍵值對(duì):
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
(7) removeValueForKey(_:)方法移除鍵值對(duì)
這個(gè)方法在鍵值對(duì)存在的情況下會(huì)移除該鍵值對(duì)并且返回被移除的值或者在沒有值的情況下返回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."
- 3.5 字典遍歷
(1) 我們可以使用for-in循環(huán)來遍歷某個(gè)字典中的鍵值對(duì)。每一個(gè)字典中的數(shù)據(jù)項(xiàng)都以(key, value)元組形式返回,并且我們可以使用臨時(shí)常量或者變量來分解這些元組:
for (airportCode, airportName) in airports {
print("\\(airportCode): \\(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
(2) 通過訪問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
(3) 用字典的keys或values屬性實(shí)例初始化與一個(gè)新的數(shù)組
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]
以上只是一些簡(jiǎn)單的概念說(fan)明(yi),如有錯(cuò)誤請(qǐng)指正,謝謝。Swift 3 學(xué)習(xí) ,后續(xù)會(huì)不斷更新。
如果你覺得我的文章對(duì)你有幫助請(qǐng)點(diǎn)喜歡哦,也可以關(guān)注我,每周至少一篇技術(shù)更新。
或者關(guān)注 我的專題 每周至少5篇高質(zhì)量文章收錄,多謝支持。
一起學(xué)習(xí),一起進(jìn)步

