一廓鞠、數(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"]