欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Swift Set集合及常用方法詳解總結(jié)

 更新時(shí)間:2021年11月06日 11:07:17   作者:Lucky_William  
Set集合為集類型,集是最簡(jiǎn)單的一種集合,存放于集中的對(duì)象不按特定方式排序,只是簡(jiǎn)單地把對(duì)象加入集合中,類似于向口袋里放東西,對(duì)集中存在的對(duì)象的訪問和操作是通過對(duì)象的引用進(jìn)行的,因此在集中不能存放重復(fù)對(duì)象

Swift 集合 Set 及常用方法

1. 創(chuàng)建Set集合

// 創(chuàng)建Set
var set: Set<Int> = [1, 2, 3]
var set2 = Set(arrayLiteral: 1, 2, 3)

2. 獲取元素

// set 獲取最小值
set.min()

// 獲取第一個(gè)元素,順序不定
set[set.startIndex]
set.first

// 通過下標(biāo)獲取元素,只能向后移動(dòng),不能向前
// 獲取第二個(gè)元素
set[set.index(after: set.startIndex)]

// 獲取某個(gè)下標(biāo)后幾個(gè)元素
set[set.index(set.startIndex, offsetBy: 2)]

3. 常用方法

// 獲取元素個(gè)數(shù)
set.count

// 判斷空集合
if set.isEmpty {
   print("set is empty")
}

// 判斷集合是否包含某個(gè)元素
if (set.contains(3)) {
    print("set contains 3")
}

// 插入
set.insert(0)

// 移除
set.remove(2)
set.removeFirst()

// 移除指定位置的元素,需要用 ! 拆包,拿到的是 Optional 類型,如果移除不存在的元素,EXC_BAD_INSTRUCTION
set.remove(at: set.firstIndex(of: 1)!)

set.removeAll()


var setStr1: Set<String> = ["1", "2", "3", "4"]
var setStr2: Set<String> = ["1", "2", "5", "6"]

// Set 取交集
setStr1.intersection(setStr2) // {"2", "1"}

// Set 取交集的補(bǔ)集
setStr1.symmetricDifference(setStr2) // {"4", "5", "3", "6"}

// Set 取并集
setStr1.union(setStr2) // {"2", "3", "1", "4", "6", "5"}

// Set 取相對(duì)補(bǔ)集(差集),A.subtract(B),即取元素屬于 A,但不屬于 B 的元素集合
setStr1.subtract(setStr2) // {"3", "4"}

var eqSet1: Set<Int> = [1, 2, 3]
var eqSet2: Set<Int> = [3, 1, 2]

// 判斷 Set 集合相等
if eqSet1 == eqSet2 {
    print("集合中所有元素相等時(shí),兩個(gè)集合才相等,與元素的順序無關(guān)")
}

let set3: Set = [0, 1]
let set4: Set = [0, 1, 2]

// 判斷子集
set3.isSubset(of: set4) // set3 是 set4 的子集,true
set3.isStrictSubset(of: set4) // set3 是 set4 的真子集,true

// 判斷超集
set4.isSuperset(of: set3) // set4 是 set3 的超集,true
set4.isStrictSuperset(of: set3) // set4 是 set3 的真超集,true

4. Set 遍歷

// 遍歷元素
for ele in set4 {
    print(ele)
}

// 遍歷集合的枚舉
for ele in set4.enumerated() {
    print(ele)
}

// 下標(biāo)遍歷
for index in set4.indices {
    print(set4[index])
}

// 從小到大排序后再遍歷
for ele in set4.sorted(by: <) {
    print(ele)
}

GitHub 源碼:SetType.playground

到此這篇關(guān)于Swift Set集合及常用方法詳解總結(jié)的文章就介紹到這了,更多相關(guān)Swift Set集合內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論