swift七-集合類型

 /*數組(Arrays*)*/
    //創建數組
    var someInts = [Int]()
    print("someInts is of type [Int] with \(someInts.count) items.") // 打印 "someInts is of type [Int] with 0 items."
    
    var threeDoubles = Array(repeating: 0.0, count: 3)
    
    //通過兩個數組相加創建一個數組
    var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
    
    var sixDoubles = threeDoubles + anotherThreeDoubles
    
    print(sixDoubles)
    
    //訪問和修改數組
    
    var shoppingList = ["Eggs", "Milk"]
    
    print("The shopping list contains \(shoppingList.count) items.")
    
    if shoppingList.isEmpty {
        print("The shopping list is empty.")
    } else {
        print("The shopping list is not empty.")
    }
    
    //使用append(_:)方法在數組后面添加新的數據項
    shoppingList.append("Flour")
    
    //使用(+=)在數組后面添加數據項(相同類型)
    shoppingList += ["Baking Powder"]
    
    //使用下標獲取數組的數據項
    var firstItem = shoppingList[0]
    
    //通過下標來改變數據項值
    shoppingList[0] = "Six eggs"
    print(shoppingList)
    shoppingList[1...2] = ["Bananas", "Apples"]
    
    //調用數組的 insert(_:at:) 方法來在某個具體索引值之前添加數據項:
    shoppingList.insert("Maple Syrup", at: 0)
    
    //remove(at:)刪除某個元素
   shoppingList.remove(at: 0)
    
    //刪除最后一項
    shoppingList.removeLast()
    //刪除所有
    // shoppingList.removeAll()
    
    //遍歷數組
    for item in shoppingList {
        print(item)
    }
    
    //如果我們同時需要每個數據項的值和索引值,可以使用 enumerated() 方法來進行數組遍歷。 enumerated() 返回 一個由每一個數據項索引值和數據值組成的元組。我們可以把這個元組分解成臨時常量或者變量來進行遍歷:
    for (index,value) in shoppingList.enumerated() {
        print("Item \(String(index + 1)):\(value)")
    }
    
    
    /************************集合*********************************/
    
    // 集合(Set)用來存儲相同類型并且沒有確定順序的值。當集合元素順序不重要時或者希望確保每個元素只出現一次 時可以使用 合而不是數組。
    //集合類型的哈希值 
    //一個類型為了存儲在集合中,該類型必須是可哈希化的--也就是說,該類型必須提供一個方法來計算它的哈希值。一個哈希值是 Int 類型的,相等的對象哈希值必須相同,比如 a==b ,因此必須 a.hashValue == b.hashValue。
    
    //創建和構造一個空的集合
    var letters = Set<Character>()
    print("letters is of type Set<Character> with \(letters.count) items.")
    letters.insert("a")
    
    //用數組字面量創建集合
    var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
    print(favoriteGenres)
    
    
    //訪問和修改一個集合
    //你可以通過 Set 的屬性和方法來訪問和修改一個 Set 。
    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.")
    }
    
    //調用 Set 的 insert(_:) 方法來添加一個新元素:
    favoriteGenres.insert("Jazz")
    
    //調用 Set 的 remove(_:) 方法去刪除一個元素,如果該值是該 Set 的一個元素則刪除該元素并且返回 被刪除的元素值,否則如果該 Set 不包含該值,則返回 nil 。另外, Set 中的所有元素可以通過它的 removeAll() 方法刪除。
    if let removedGenre = favoriteGenres.remove("Rock") {
        print("\(removedGenre)? I'm over it.")
    } else {
        print("I never much cared for that.")
    }
    
    //使用 contains(_:) 方法去檢查 Set 中是否包含一個特定的值:
    if favoriteGenres.contains("Funk") {
        
        print("I get up on the good foot.")
        
    } else {
        
        print("It's too funky in here.")
        
    }
    
    //遍歷集合
    for genre in favoriteGenres {
        print("\(genre)")
    }
    
    //Swift 的 Set 類型沒有確定的順序,為了按照特定順序來遍歷一個 Set 中的值可以使用 sorted() 方法,它將返回一個有序數組,這個數組的元素排列順序由操作符'<'對元素進行比較的結果來確定.
    for genre in favoriteGenres.sorted() {
        print("\(genre)")
    }
    
    
    //集合操作
    //使用 intersection(_:) 方法根據兩個集合中都包含的值創建的一個新的集合。
    //使用 symmetricDifference(_:) 方法根據在一個集合中但不在兩個集合中的值創建一個新的集合。
    //使用 union(_:) 方法根據兩個集合的值創建一個新的集合。
    //使用 subtracting(_:) 方法根據不在該集合中的值創建一個新的集合。
    
    let oldDigts:Set = [1,3,5,7,9]
    let evenDigts:Set = [0,2,4,6,8]
    let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
    
    oldDigts.union(evenDigts).sorted()
    oldDigts.subtracting(singleDigitPrimeNumbers).sorted()
    oldDigts.symmetricDifference(singleDigitPrimeNumbers).sorted()
    print(oldDigts.union(evenDigts).sorted())
    print(oldDigts.subtracting(singleDigitPrimeNumbers).sorted())
    print(oldDigts.symmetricDifference(singleDigitPrimeNumbers).sorted())
    
    
    //集合成員關系和相等
    //使用“是否相等”運算符( == )來判斷兩個集合是否包含全部相同的值。
    //使用 isSubset(of:) 方法來判斷一個集合中的值是否也被包含在另外一個集合中。
    //使用 isSuperset(of:) 方法來判斷一個集合中包含另一個 合中所有的值。
    //使用 isStrictSubset(of:) 或者 isStrictSuperset(of:) 方法來判斷一個集合是否是另外一個集合的子集合或者父 合并且兩個集合并不相等。
    //使用 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
    
    //字典
    //字典類型簡化語法:Swift 的字典使用 Dictionary<Key, Value> 定義,其中 Key 是字典中鍵的數據類型, Value 是字典中對應于這些 鍵所存儲值的數據類型。
    
    //創建字典
    var namesOfIntegers = [NSInteger: String]()
    // namesOfIntegers 是一個空的 [Int: String] 字典
    
    namesOfIntegers[16] = "sixteen"
    // namesOfIntegers 現在包含一個鍵值對
    
    namesOfIntegers = [:]
    // namesOfIntegers 又成為了一個 [Int: String] 類型的空字典
    
    //用字典字面量創建字典
    var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
    
    //訪問和修改字典
    //通過字典的只讀屬性 count 來獲取某個字典的數據項數量:
    print("The dictionary of airports contains \(airports.count) items.")
    // 打印 "The dictionary of airports contains 2 items."(這個字典有兩個數據項)
    
    //字典的 updateValue(_:forKey:) 方法可以設置或者更新特定鍵對應的值。返回跟新之前的值
    if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
        print("The old value for DUB was \(oldValue).")
    }
    print(airports)
    
    //字典遍歷
    for (airportCode, airportName) in airports {
        print("\(airportCode): \(airportName)")
    }
    
    //通過訪問keys或者values屬性,我們也可以遍歷字典的鍵或者值:
    for airportCode in airports.keys {
        print("Airport code: \(airportCode)")
    }
    
    for airportName in airports.values {
        print("Airport name: \(airportName)")
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容