Swift學習筆記(5):集合類型

來源:互聯網
上載者:User

標籤:指定元素   dict   種類   遍曆   remove   聲明   letter   contains   air   

目錄:

  • 數組:Array
  • 集合:Set
  • 字典:Dictionary

Swift提供Array(有序集合資料)、Set(無序無重複集合)和Dictionary(無序索引值對集合)三種基本集合類型來儲存明確資料類型的集合資料。

使用var將集合聲明為變數,可以在建立之後添加、移除、修改集合內資料項目。如果使用let將集合聲明為常量,則它的大小和內容就都不可改變。

 

數組:Array

初始化和賦值:

var someInts = [Int]()      // 建立指定資料類型的空數組someInts = []               // 為已知資料類型的資料賦空值// threeDoubles 是一種 [Double] 數組,等價於 [0.0, 0.0, 0.0]var threeDoubles = Array(repeating: 0.0, count: 3)  // 建立帶有預設值的資料// sixDoubles 被推斷為 [Double],等價於 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]var anotherThreeDoubles = Array(repeating: 2.5, count: 3)var sixDoubles = threeDoubles + anotherThreeDoubles // 通過+組合兩個相同資料類型數組var shoppingList = ["Eggs", "Milk"]                 // 數組字面量構造數組var shoppingList: [String] = ["Eggs", "Milk"]       // 與上面等價

我們可以使用下標或屬性和方法來訪問和修改數組:

shoppingList.count               // 擷取數組元素個數// 使用isEmpty屬性判斷數組書否為空白if shoppingList.isEmpty {    print("The shopping list is empty.")}shoppingList.append("Flour")     // 使用append()方法追加資料元素shoppingList += ["Chocolate Spread", "Cheese", "Butter"]  // 使用+=追加資料元素var firstItem = shoppingList[0]  // 使用數組下標訪問元素,第一項是"Eggs"shoppingList[0] = "Six eggs"     // 使用下標改變數組元素shoppingList[4...6] = ["Bananas", "Apples"]  // 將4~6的3個元素替換為右邊的2個元素shoppingList.insert("Maple Syrup", at: 0)    // 使用insert(_:at:)方法在具體索引之前添加元素let mapleSyrup = remove(at: 0)   // 移除制定索引的數組元素let apples = shoppingList.removeLast()       // 移除數組最後一項元素

注意:

?不可以用下標訪問的形式去在數組尾部添加新項
?數組起始索引為0,最大索引為 count-1

使用for-in遍曆數組:

for item in shoppingList {    print(item)}

使用數組enumerated()方法遍曆數組返回元素值和索引:

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

  

集合:Set

一種類型的資料需要儲存在Set中,該類型必須是可雜湊的,雜湊實值型別為Int。Swift基礎資料型別 (Elementary Data Type)都可雜湊,沒有關聯值的枚舉也可雜湊。

自訂資料類型要作為Set元素儲存時,必須實現Swift語言的Hashable和Equatable協議。 

初始化和賦值:

var letters = Set<Character>() // 建立一個空Sets集合letters = []                   // 已知資料類型,賦值一個空Sets集合, letters依然是Set<Character>類型// 使用數組字面量構造一個集合var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] 

訪問和修改Set集合:

favoriteGenres.count          // 擷取Set集合的元素個數// 使用isEmpty屬性判斷Set集合是否為空白if favoriteGenres.isEmpty {    print("As far as music goes, I‘m not picky.")}favoriteGenres.insert("Jazz") // 插入一個Set集合元素let removedGenre = favoriteGenres.remove("Rock")   // 刪除一個Set集合元素favoriteGenres.removeAll()    // 刪除集合所有元素// 使用contains()方法判斷Set集合是否包含指定元素if favoriteGenres.contains("Funk") {    print("I get up on the good foot.")}

使用for-in遍曆Set集合:

for genre in favoriteGenres {    print("\(genre)")}

使用sorted()返回一個已排序的數字來遍曆Set集合:

for genre in favoriteGenres.sorted() {     print("(genre)")}// prints "Classical"// prints "Hip hop"// prints "Jazz

 

字典:Dictionary

初始化和賦值:

var namesOfIntegers = [Int: String]  // 建立一個空字典namesOfIntegers = [:]                // 給已知資料類型字典賦空值// 字面量構造一個字典var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

訪問和修改Dictionary集合:

airports.count              // 擷取字典元素個數// 判斷字典是否為空白if airports.isEmpty {    print("The airports dictionary is empty.")}airports["LHR"] = "London"  //使用下標為指定key字典元素賦值或變更值// 使用字典的updateValue()方法更新字典元素並檢驗更新結果if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {     print("The old value for DUB was (oldValue).")}// 判斷字典中是否存在指定key關聯元素if let airportName = airports["DUB"] {    print("The name of the airport is (airportName).")}airports["APL"] = nil        // 刪除字典指定key關聯的元素// 使用字典removedValue()方法刪除指定元素並檢驗刪除結果if let removedValue = airports. removeValue(forKey: "DUB") {    print("The removed airport‘s name is (removedValue).")}

使用for-in遍曆字典:

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: LHRfor airportName in airports.values {    print("Airport name: (airportName)")}// Airport name: Toronto Pearson// Airport name: London Heathrow

 

 

聲明:該系列內容均來自網路或電子書籍,只做學習總結!

Swift學習筆記(5):集合類型

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.