數(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"]