• <small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small><xmp id="w8oog"><td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><xmp id="w8oog"><td id="w8oog"></td>
  • <td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small>
  • <small id="w8oog"></small><td id="w8oog"></td>
    免費開源的iOS開發學習平臺

    Swift: 5.2 集合類型-集合

    集合其實就是一個哈希表,它跟數組的區別在于集合不是連續的,集合里面的值具有唯一性。集合常用在經常性的插入、刪除和查找元素的情況下。

    • 集合的常見操作跟數組的一致,不過集合類型是Set<Element>,如果類型可以推斷出來,同樣可以簡寫成Set。集合的初始化也可以用數組的字面量的方式進行。同樣的,集合通過insert(_:)函數插入值,通過remove(_:)函數來刪除值,不過如果刪除的值不在集合中,返回值可能為nil。也可以通過removeAll()函數來刪除集合中所有的值。集合也是可遍歷的,雖然集合是無序的,不過可以用sorted()函數返回集合的排序后的序列。下面程序展示了集合的基本用法。
    var fullSet : Set<String> = ["HTML5","App","XWx"]
    //也可以簡寫成如下:
    var shortSet : Set = ["HTML5","App","XWx"]
    
    shortSet.insert("Vovo")
    
    //刪除一個元素,元素可能為nil
    if let removed = shortSet.remove("HTML5"){
        print("\(removed)? 被刪掉了")
    }else{
        print("不存在這個元素")
    }
    
    //查找某個元素
    if let contained = shortSet.contains("Woo"){
        print("找到了")
    }else{
        print("沒找到")
    }
    
    //遍歷集合
    for item in shortSet {
        print("\(item)")
    }
    //按照首字母進行默認排序后的序列
    for item in shortSet.sorted(){
        print("\(item)")
    }
    

    運行結果如下圖。

    • 可以很方便的對兩個同類型的集合執行合并,獲取集合的交集、補集以及差集。還可以很方便的通過函數判斷兩個集合是否是父子集的關系。使用到的函數如下示例中。
    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()
    // 獲取交集
    oddDigits.intersection(evenDigits).sorted()
    // 獲取差集,在oaddDigits并且不在singleDigitPrimeNumbers中
    oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
    // 獲取oddDigits和singleDigitPrimeNumbers的補集,也就是并集-交集
    oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
    
    let houseAnimals: Set = ["
    
     //子集判斷
    houseAnimals.isSubset(of: farmAnimals)
    // 父集判斷
    farmAnimals.isSuperset(of: houseAnimals)
    // 是否沒有交集
    farmAnimals.isDisjoint(with: cityAnimals)
    
    

    代碼運行結果如下圖。

    示例代碼

    https://github.com/99ios/23.5.2

    ijzzijzzij亚洲大全|天天狠天天透天干天天|日本一本加勒比五月天伊人久久|久久久噜噜噜久久中文字幕色伊伊
  • <small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small><xmp id="w8oog"><td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><xmp id="w8oog"><td id="w8oog"></td>
  • <td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small>
  • <small id="w8oog"></small><td id="w8oog"></td>