1. 創(chuàng)建Set集合
1
2
3
|
/ / 創(chuàng)建 Set var set : Set < Int > = [ 1 , 2 , 3 ] var set2 = Set (arrayLiteral: 1 , 2 , 3 ) |
2. 獲取元素
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/ / set 獲取最小值 set . min () / / 獲取第一個(gè)元素,順序不定 set [ set .startIndex] set .first / / 通過(guò)下標(biāo)獲取元素,只能向后移動(dòng),不能向前 / / 獲取第二個(gè)元素 set [ set .index(after: set .startIndex)] / / 獲取某個(gè)下標(biāo)后幾個(gè)元素 set [ set .index( set .startIndex, offsetBy: 2 )] |
3. 常用方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
/ / 獲取元素個(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 類(lèi)型,如果移除不存在的元素,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è)集合才相等,與元素的順序無(wú)關(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 遍歷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/ / 遍歷元素 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)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/java_android_man/article/details/121171452