Swift 集合 Set 及常用方法
1. 創建Set集合
// 創建Set
var set: Set<Int> = [1, 2, 3]
var set2 = Set(arrayLiteral: 1, 2, 3)
2. 獲取元素
// set 獲取最小值
set.min()
// 獲取第一個元素,順序不定
set[set.startIndex]
set.first
// 通過下標獲取元素,只能向后移動,不能向前
// 獲取第二個元素
set[set.index(after: set.startIndex)]
// 獲取某個下標后幾個元素
set[set.index(set.startIndex, offsetBy: 2)]
3. 常用方法
// 獲取元素個數
set.count
// 判斷空集合
if set.isEmpty {
print("set is empty")
}
// 判斷集合是否包含某個元素
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 取交集的補集
setStr1.symmetricDifference(setStr2) // {"4", "5", "3", "6"}
// Set 取并集
setStr1.union(setStr2) // {"2", "3", "1", "4", "6", "5"}
// Set 取相對補集(差集),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("集合中所有元素相等時,兩個集合才相等,與元素的順序無關")
}
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)
}
// 下標遍歷
for index in set4.indices {
print(set4[index])
}
// 從小到大排序后再遍歷
for ele in set4.sorted(by: <) {
print(ele)
}
GitHub 原始碼:SetType.playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/349668.html
標籤:其他
