數(shù)組
- 創(chuàng)建一個(gè)空數(shù)組
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// 打印 "someInts is of type [Int] with 0 items."
//注意刃泌,通過構(gòu)造函數(shù)的類型凡壤, someInts 的值類型被推斷為 [Int] 。
someInts.append(3)
// someInts 現(xiàn)在包含一個(gè) Int 值
someInts = []
// someInts 現(xiàn)在是空數(shù)組耙替,但是仍然是 [Int] 類型的亚侠。
- 創(chuàng)建一個(gè)帶默認(rèn)值的數(shù)組
Swift 中的 Array 類型還提供一個(gè)可以創(chuàng)建特定大小并且所有數(shù)據(jù)都被默認(rèn)的構(gòu)造方法。我們可以把準(zhǔn)備加入新 數(shù)組的數(shù)據(jù)項(xiàng)數(shù)量( count )和適當(dāng)類型的初始值( repeating )傳入數(shù)組構(gòu)造函數(shù):
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles 是一種 [Double] 數(shù)組林艘,等價(jià)于 [0.0, 0.0, 0.0]
- 通過兩個(gè)數(shù)組相加創(chuàng)建一個(gè)數(shù)組
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles 被推斷為 [Double]盖奈,等價(jià)于 [2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles 被推斷為 [Double],等價(jià)于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
- 用數(shù)字字面量構(gòu)造數(shù)組
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList 已經(jīng)被構(gòu)造并且擁有兩個(gè)初始項(xiàng)狐援。
shoppingList 變量被聲明為“字符串值類型的數(shù)組“钢坦,記作 [String] 究孕。 因?yàn)檫@個(gè)數(shù)組被規(guī)定只有 String 一種 數(shù)據(jù)結(jié)構(gòu),所以只有 String 類型可以在其中被存取爹凹。 在這里厨诸, shoppingList 數(shù)組由兩個(gè) String 值( "Eggs" 和 "Milk" )構(gòu)造,并且由數(shù)組字面量定義禾酱。
- 訪問和修改數(shù)組
可以使用數(shù)組的只讀屬性 count 來獲取數(shù)組中的數(shù)據(jù)項(xiàng)數(shù)量:
print("The shopping list contains \(shoppingList.count) items.")
// 輸出 "The shopping list contains 2 items."(這個(gè)數(shù)組有2個(gè)項(xiàng))
使用布爾屬性 isEmpty 作為一個(gè)縮寫形式去檢查 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."(shoppinglist 不是空的)
也可以使用 append(_:) 方法在數(shù)組后面添加新的數(shù)據(jù)項(xiàng):
shoppingList.append("Flour")
// shoppingList 現(xiàn)在有3個(gè)數(shù)據(jù)項(xiàng)微酬,有人在攤煎餅
除此之外,使用加法賦值運(yùn)算符( += )也可以直接在數(shù)組后面添加一個(gè)或多個(gè)擁有相同類型的數(shù)據(jù)項(xiàng):
shoppingList += ["Baking Powder"]
// shoppingList 現(xiàn)在有四項(xiàng)了
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList 現(xiàn)在有七項(xiàng)了
可以直接使用下標(biāo)語法來獲取數(shù)組中的數(shù)據(jù)項(xiàng)颤陶,把我們需要的數(shù)據(jù)項(xiàng)的索引值放在直接放在數(shù)組名稱的方括號(hào)
中:
var firstItem = shoppingList[0]
// 第一項(xiàng)是 "Eggs"
我們也可以用下標(biāo)來改變某個(gè)已有索引值對(duì)應(yīng)的數(shù)據(jù)值:
shoppingList[0] = "Six eggs"
// 其中的第一項(xiàng)現(xiàn)在是 "Six eggs" 而不是 "Eggs"
調(diào)用數(shù)組的 insert(_:at:) 方法來在某個(gè)具體索引值之前添加數(shù)據(jù)項(xiàng):
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList 現(xiàn)在有7項(xiàng)
// "Maple Syrup" 現(xiàn)在是這個(gè)列表中的第一項(xiàng)
我們可以使用 remove(at:) 方法來移除數(shù)組中的某一項(xiàng)
let mapleSyrup = remove(at: 0)
// 索引值為0的數(shù)據(jù)項(xiàng)被移除
// shoppingList 現(xiàn)在只有6項(xiàng)颗管,而且不包括 Maple Syrup
// mapleSyrup 常量的值等于被移除數(shù)據(jù)項(xiàng)的值 "Maple Syrup"
- 數(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)的值和索引值,可以使用 enumerated() 方法來進(jìn)行數(shù)組遍歷滓走。 enumerated() 返回 一個(gè)由每一個(gè)數(shù)據(jù)項(xiàng)索引值和數(shù)據(jù)值組成的元組垦江。我們可以把這個(gè)元組分解成臨時(shí)常量或者變量來進(jìn)行遍歷:
for (index, value) in shoppingList. enumerated() {
print("Item \(String(index + 1)): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
集合
合類型的哈希值
一個(gè)類型為了存儲(chǔ)在 合中,該類型必須是可哈辖练剑化的--也就是說比吭,該類型必須提供一個(gè)方法來計(jì)算它的哈希 值。一個(gè)哈希值是 Int 類型的姨涡,相等的對(duì)象哈希值必須相同衩藤,比如 a==b ,因此必須 a.hashValue == b.hashValu e。
Swift 的所有基本類型(比如 String , Int , Double 和 Bool )默認(rèn)都是可哈咸纹化的赏表,可以作為 合的值的類型或 者字典的鍵的類型怖喻。沒有關(guān)聯(lián)值的枚舉成員值(在枚舉有講述)默認(rèn)也是可哈厦校化的哗蜈。創(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.")
// 打印 "letters is of type Set<Character> with 0 items."
通過一個(gè)空的數(shù) 組字面量創(chuàng)建一個(gè)空的 Set :
letters.insert("a")
// letters 現(xiàn)在含有1個(gè) Character 類型的值
letters = []
// letters 現(xiàn)在是一個(gè)空的 Set, 但是它依然是 Set<Character> 類型
- 用數(shù)組字面量構(gòu)建集合
創(chuàng)建一個(gè)稱之為 favoriteGenres 的 合來存儲(chǔ) String 類型的值:
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres 被構(gòu)造成含有三個(gè)初始值的 合
- 訪問和修改一個(gè)集合
一個(gè) Set 中元素的數(shù)量,可以使用其只讀屬性 count :
print("I have \(favoriteGenres.count) favorite music genres.")
// 打印 "I have 3 favorite music genres."
使用布爾屬性 isEmpty 作為一個(gè)縮寫形式去檢查 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."
你可以通過調(diào)用 Set 的 insert(_:) 方法來添加一個(gè)新元素:
favoriteGenres.insert("Jazz")
// favoriteGenres 現(xiàn)在包含4個(gè)元素
調(diào)用 Set 的 remove(_:) 方法去刪除一個(gè)元素,另外音比, Set 中的所有元素可以通過它的 removeAl l() 方法刪除
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(_:) 方法去檢查 Set 中是否包含一個(gè)特定的值:
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."
- 遍歷一個(gè)集合
在一個(gè) for-in 循環(huán)中遍歷一個(gè) Set 中的所有值稽犁。
for genre in favoriteGenres {
print("\(genre)")
}
// Classical
// Jazz
// Hip hop
按照特定順序來遍歷一個(gè) Set 中的值可以使用 sorted() 方法已亥,它將返回一個(gè)有序數(shù)組
for genre in favoriteGenres.sorted() {
print("(genre)")
}
// prints "Classical"
// prints "Hip hop"
// prints "Jazz
集合操作
- 基本集合操作
- 使用 intersection(_:) 方法根據(jù)兩個(gè) 合中都包含的值創(chuàng)建的一個(gè)新的 合虑椎。
- 使用 symmetricDifference(_:) 方法根據(jù)在一個(gè) 合中但不在兩個(gè) 合中的值創(chuàng)建一個(gè)新的 合俱笛。
- 使用 union(_:) 方法根據(jù)兩個(gè) 合的值創(chuàng)建一個(gè)新的 合迎膜。
- 使用 subtracting(_:) 方法根據(jù)不在該 合中的值創(chuàng)建一個(gè)新的
- 集合成員關(guān)系和相等
- 使用“是否相等”運(yùn)算符( == )來判斷兩個(gè) 合是否包含全部相同的值。
- 使用 isSubset(of:) 方法來判斷一個(gè) 合中的值是否也被包含在另外一個(gè) 合中零抬。
- 使用 isSuperset(of:) 方法來判斷一個(gè) 合中包含另一個(gè) 合中所有的值宽涌。
- 使用 isStrictSubset(of:) 或者 isStrictSuperset(of:) 方法來判斷一個(gè) 合是否是另外一個(gè) 合的子 合或 者父 合并且兩個(gè) 合并不相等。
- 使用 isDisjoint(with:) 方法來判斷兩個(gè) 合是否不含有相同的值(是否沒有交 )。
字典
- 創(chuàng)建一個(gè)空字典
var namesOfIntegers = Int: String
// namesOfIntegers 是一個(gè)空的 [Int: String] 字典
namesOfIntegers[16] = "sixteen"
// namesOfIntegers 現(xiàn)在包含一個(gè)鍵值對(duì)
namesOfIntegers = [:]
// namesOfIntegers 又成為了一個(gè) [Int: String] 類型的空字典
- 用字典字面量創(chuàng)建字典
一個(gè)鍵值對(duì)是一個(gè) key 和一個(gè) value 的結(jié)合體段直。在字典字面量中鸯檬,每一個(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]
- 訪問和修改字典
通過字典的只讀屬性 count 來獲取某個(gè)字典的數(shù)據(jù)項(xiàng)數(shù)量:
print("The dictionary of airports contains (airports.count) items.")
// 打印 "The dictionary of airports contains 2 items."(這個(gè)字典有兩個(gè)數(shù)據(jù)項(xiàng))
使用布爾屬性 isEmpty 作為一個(gè)縮寫形式去檢查 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."
使用一個(gè)恰當(dāng)類型的鍵作為下標(biāo)索引玲昧,并且分配恰當(dāng)
類型的新值:
airports["LHR"] = "London"
// airports 字典現(xiàn)在有三個(gè)數(shù)據(jù)項(xiàng)
我們也可以使用下標(biāo)語法來改變特定鍵對(duì)應(yīng)的值:
airports["LHR"] = "London Heathrow"
// "LHR"對(duì)應(yīng)的值 被改為 "London Heathrow
作為另一種下標(biāo)方法酌呆,字典的 updateValue(_:forKey:) 方法可以設(shè)置或者更新特定鍵對(duì)應(yīng)的值衡载。updateValue(_:forKey:) 方法會(huì)返回對(duì)應(yīng)值的類型的可選值隙袁。
可以使用下標(biāo)語法來通過給某個(gè)鍵的對(duì)應(yīng)值賦值為 nil 來從字典里移除一個(gè)鍵值對(duì):
airports["APL"] = "Apple Internation"
// "Apple Internation" 不是真的 APL 機(jī)場(chǎng), 刪除它
airports["APL"] = nil
// APL 現(xiàn)在被移除了
此外, removeValue(forKey:) 方法也可以用來在字典中移除鍵值對(duì)菩收。
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."
- 字典遍歷
使用 for-in 循環(huán)來遍歷某個(gè)字典中的鍵值對(duì)。
for (airportCode, airportName) in airports {
print("(airportCode): (airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
通過訪問 或者 屬性娜饵,我們也可以遍歷字典的鍵或者值:
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