Swift3.0集合類(lèi)型(Collection Types)

Swift一樣有著三種基本集合類(lèi)型,數(shù)組,集合,字典。


在Swift中,這三種類(lèi)型總是很明確要存儲(chǔ)的類(lèi)型,這意味著不能再插入時(shí)犯錯(cuò)。

集合的可變性(Mutability of Collections)

當(dāng)你用"var"來(lái)創(chuàng)建一個(gè)數(shù)組、集合、字典的時(shí)候,它就是可變的。

數(shù)組(Arrays)

Swift的Array橋接了Foundation的NSArray類(lèi)

創(chuàng)建一個(gè)空數(shù)組(Creating an Empty Array)
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 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]
創(chuàng)建有默認(rèn)值的數(shù)組(Creating an Array with a Default Value)
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
通過(guò)兩個(gè)數(shù)組連接來(lái)創(chuàng)建一個(gè)數(shù)組(Creating an Array by Adding Two Arrays Together)

和字符串一樣,可以通過(guò)"+"直接連接,??:

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]
使用字面值來(lái)創(chuàng)建數(shù)組(Creating an Array with an Array Literal)

這個(gè)方式最簡(jiǎn)單,也最常用:

//完整寫(xiě)法:var shoppingList: [String] = ["Eggs", "Milk"]
var shoppingList = ["Eggs", "Milk"]
//shoppingList has been initialized with two initial items

這種情況下創(chuàng)建的數(shù)組,只能存儲(chǔ)String類(lèi)型,如果是別的類(lèi)型會(huì)拋出錯(cuò)誤。

接收/修改數(shù)組(Accessing and Modifying an Array)
  • 用"count"屬性,讀取共有多少個(gè)數(shù)值。
  • 用"isEmpty"屬性,判斷是否為空
  • 用"append(_:)"方法追加一個(gè)元素:
shoppingList.append("Bread")
//shoppingList now contains 3 items

也可以用"+="來(lái)追加元素

shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items
  • 通過(guò)下標(biāo)索引值來(lái)獲取(修改)對(duì)應(yīng)元素。同樣可以通過(guò)下標(biāo)范圍來(lái)修改對(duì)應(yīng)元素。
shoppingList[4...6] = ["Bananas", "Apples"]
//shoppingList now contains 6 items

注意,不能用下標(biāo)來(lái)追加元素。

  • 使用"insert(_:at:)"方法來(lái)插入元素
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list
  • 和插入類(lèi)似,可以用"remove(at:)"方法來(lái)刪除對(duì)應(yīng)元素。想要?jiǎng)h除最后一個(gè)元素的時(shí)候可以使用"removeLast()"方法。

當(dāng)數(shù)組為空時(shí)(count = 0),數(shù)組的最大有效索引值總是count -1,因?yàn)樗饕凳菑?開(kāi)始的。

數(shù)組的遍歷(Iterating Over an Array)

可以使用"for-in"循環(huán)。當(dāng)需要索引值的時(shí)候,可以使用"enumerated()"方法,??:


??

index和value可以任意命名。

集合(Sets)

只能添加遵守Hashable協(xié)議的類(lèi)型。

創(chuàng)建和初始化一個(gè)空的集合(Creating and Initializing an Empty Set)
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"

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ù)組字面量創(chuàng)建一個(gè)集合(Creating a Set with an Array Literal)
// 完整寫(xiě)法:var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
接收/修改集合(Accessing and Modifying a Set)
  • 通過(guò)"count"屬性來(lái)訪問(wèn)元素個(gè)數(shù)。
  • 通過(guò)"isEmpty"屬性來(lái)判斷元素個(gè)數(shù)是否為0。
  • 通過(guò)"insert(_:)"方法來(lái)追加新元素。
  • 通過(guò)"remove(_:)"方法來(lái)刪除元素。這個(gè)方法返回刪除之,如果返回為nil則說(shuō)明集合中沒(méi)有該數(shù)值,??:
if let removeGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.")
} else {
    print("I never much cared for that.")
}

// Prints "Rock? I'm over it."

  • 通過(guò)"contains(_:)"方法來(lái)判斷是否包含這個(gè)元素。
集合的遍歷(Iterating Over a Set)
  • 可以使用"for-in"循環(huán)進(jìn)行遍歷。
  • 因?yàn)镾wift的Set類(lèi)型是沒(méi)有順序的,可以用"sorted()"方法進(jìn)行升序排序,該方法返回的是一個(gè)數(shù)組,??:
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz

Performing Set Operations(不知道怎么翻譯了??)

基本的集合操作(Fundamental Set Operations)
基本的集合操作
  • 通過(guò)"intersection(_:)"方法得到兩個(gè)集合的交集。(a ∩ b)
  • 通過(guò)"symmetricDifference(_:)"方法得到除去包含兩個(gè)集合的值,并且除去都包含的部分。(a ∪ b - a ∩ b)
  • 通過(guò)"union(_:)"方法得到兩個(gè)集合的并集。(a ∪ b)
  • 通過(guò)"subtracting(_:)"方法得到前者與后者的差集。(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]
集合的成員和相等(Set Membership and Equality)
  • 通過(guò)"=="判斷兩個(gè)集合是否包含所有相同的元素
  • 通過(guò)"isSubset(of:)"方法判斷前者是否是后者的子集。
  • 通過(guò)"isSuperset(of:)"方法判斷后者是否是前者的子集。
  • 通過(guò)"isStrictSubset(of:)"或者"isStrictSuperset(of:)"判斷是否是真子集(為子集,且不相等)。
  • 通過(guò)"isDisjoint(with:)"方法判斷兩個(gè)集合是否有相同的元素,就是判斷兩個(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

字典(Dictionaries)

key必須遵守Hashable協(xié)議。

創(chuàng)建空字典(Creating an Empty Dictionary)
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]
通過(guò)字面量來(lái)創(chuàng)建字典(Creating a Dictionary with a Dictionary Literal)
//完整寫(xiě)法
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
接收/修改字典(Accessing and Modifying a Dictionary)
  • 通過(guò)"count"屬性來(lái)訪問(wèn)有多少鍵值對(duì)。
  • 通過(guò)"isEmpty"屬性來(lái)訪問(wèn)是否為空。
  • 可以使用下標(biāo)語(yǔ)法來(lái)追加、修改鍵值對(duì)。
airports["LHR"] = "London"
// the airports dictionary now contains 3 items

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

也可以通過(guò)updateValue(_:forKey:)來(lái)完成追加、修改功能。當(dāng)有該key時(shí),返回舊值(old value);當(dāng)沒(méi)有該key時(shí),返回nil,并且創(chuàng)建新的鍵值對(duì)。

  • 可以使用下標(biāo)方法來(lái)刪除鍵值對(duì),方法是直接將key設(shè)為nil。
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

或者使用"removeValue(forKey:)"方法來(lái)刪除鍵值對(duì),如果有則返回刪除的值,如果沒(méi)有則返回nil。

字典的遍歷(Iterating Over a Dictionary)

使用"for-in"循環(huán)來(lái)遍歷,返回的是(key, value)的元組,??:

for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow

也可以通過(guò)字典的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
  • 如果你創(chuàng)建一個(gè)key或者value的數(shù)組,可以通過(guò)"keys"或"values"的屬性:
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]

let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]
  • Swift的字典是沒(méi)有順序的,只能通過(guò)對(duì)keys和values使用"sorted()"方法進(jìn)行排序。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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